From 3a43eaa4169c83f1f5afa4dde7f6ccb3b7fd9a4e Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Tue, 10 Nov 2026 10:30:23 +0800 Subject: [PATCH 01/13] docs(rfc): propose rag document knowledge bases --- docs/en/rfcs/0000-rag-knowledge-base.md | 319 ++++++++++++++++++++++++ docs/zh/rfcs/0000-rag-knowledge-base.md | 251 +++++++++++++++++++ 2 files changed, 570 insertions(+) create mode 100644 docs/en/rfcs/0000-rag-knowledge-base.md create mode 100644 docs/zh/rfcs/0000-rag-knowledge-base.md diff --git a/docs/en/rfcs/0000-rag-knowledge-base.md b/docs/en/rfcs/0000-rag-knowledge-base.md new file mode 100644 index 0000000000..23cf559ae7 --- /dev/null +++ b/docs/en/rfcs/0000-rag-knowledge-base.md @@ -0,0 +1,319 @@ +--- +title: "RFC 0000: Document knowledge bases with rag Artifacts" +description: "A proposal for plugin-based knowledge bases with immutable document Sources, versioned chunks, hybrid retrieval, and recoverable processing." +--- + +- Proposal Name: `rag_knowledge_base` +- Start Date: 2026-11-10 +- RFC PR: [#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) +- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) + +# Summary + +Add document knowledge bases through one document Source plugin and two Artifact families: `document` and `rag`. +A Scope can contain multiple user-created `rag` Artifacts. Users import files into a selected `rag`; background work +parses immutable input, produces a whole-document Artifact with separately stored chunks, associates it with that +knowledge base, and publishes full-text/vector indexes. This proposal defines design intent, not released APIs. + +# Motivation + +Business descriptions and task SOPs need passage retrieval with exact evidence, explicit updates, and deletion. +Extracted memories complement this use case but do not preserve all document content. A knowledge base must keep +original input, processed content, and searchable versions distinct so that failed processing cannot corrupt an +existing result and manual corrections do not masquerade as original evidence. + +Reuse PowerContext's Source definitions, Artifact management, plugin registration, Scope authorization, processing +supervision, and persistence. Add the document-specific contracts they do not yet provide instead of introducing +a parallel knowledge-base object system or a general workflow engine. + +# Guide-level explanation + +A Scope remains a project or workspace and the initial authorization boundary. A knowledge base is a `rag` Artifact +within that Scope, with its own name and processing/retrieval configuration. Renaming or deleting it does not rename +or delete the Scope. Knowledge bases in the same Scope are not separate confidentiality boundaries. + +For example, a team creates `Product docs` and `Operations SOPs` in one Scope: + +1. Create both empty `rag` Artifacts through Artifact management; no document input is required. +2. Import Markdown into `Product docs` and a standalone text image into `Operations SOPs`. +3. Receive durable import receipts and inspect parsing, indexing, and failure status. +4. Search either knowledge base, or explicitly select both. Documents appear automatically after processing and + become searchable after index publication; users do not manually attach generated documents. +5. Replace an original file or edit an existing chunk. A new document revision becomes searchable only after its + indexes are ready. A failed update leaves the previous published revision available unless revoked or removed. + +The initial release supports Markdown and independently imported images using RapidOCR with ONNX Runtime. +Markdown image references are preserved without fetching or OCR-processing their targets. SQLite, SeekDB, and +OceanBase must each support the complete functional workflow; one deployment uses one selected backend. + +Plain TXT, PDF, Office, automatic synchronization, production reranking, agentic retrieval, a complete management +UI, and a tens-of-thousands-of-documents benchmark are not initial acceptance requirements. Task status and recovery +APIs must nevertheless support a future UI. Applications remain responsible for answering questions from results. + +# Reference-level explanation + +## 1. Identity, ownership, and provenance + +```text +Scope + +-- rag K1 -- membership --> document D1 -- revisions --> chunks + +-- rag K2 -- membership --> document D2 -- revisions --> chunks + ^ +immutable document Source -------+ content provenance +``` + +| Object | Identity and responsibility | +| --- | --- | +| `rag` Artifact | User-created configuration and collection identity; members and processing progress do not create configuration revisions | +| Document Source | Immutable original input descriptor: original path, managed snapshot reference, digest, media type, and captured metadata | +| `document` Artifact | One whole logical document, with a stable ID and increasing content revisions; initially belongs to exactly one `rag` | +| Chunk | Internal content and retrieval unit of a document revision, not a Source or independent Artifact | +| Index generation | A `rag`-scoped index configuration/build, separate from content revisions and plugin registration generations | + +Logical document identity is `(scope, rag, source_namespace, external_key)`. Reimporting that identity updates the +same document; importing the same path into another `rag` creates a separate document. Content digests do not merge +logical identities. An immutable Source may be explicitly reused by multiple knowledge bases in the same Scope; +this does not create cross-Scope Source identity or shared document ownership. + +Source lineage, `rag` membership, and the searchable revision selection are separate relationships. Tags cannot +substitute for ownership. Original paths aid provenance; reads use the captured immutable snapshot rather than +whatever currently exists at that path. Raw Markdown bytes and original images live in an OpenDAL-managed local +directory, using the existing OpenDAL/`opendalfs` integration where suitable. + +Define a dedicated document Source type, provisionally `knowledge-document-input`. Only the document pipeline may +directly consume it. Enforce this at input selection, execution, and commit validation, not just through a naming +convention. Do not automatically expose it through generic evidence feeds consumed by other Artifact families. +Parsing output, OCR text, chunks, index pointers, and progress never mutate the Source payload. + +## 2. Plugin responsibilities and framework integration + +| Logical plugin | Owned behavior | +| --- | --- | +| Document Source | File validation, immutable snapshots, Source acceptance, and authorized original-content reads | +| `document` Artifact | Parsing, OCR, chunking, content revisions, chunk reads, manual edits, and evidence mappings | +| `rag` Artifact | Configuration, membership, index generations, publication, hybrid retrieval, and selected multi-base queries | + +These are three logical plugins, not three required processes or distributions. Parser/OCR/chunker implementations +are replaceable components within `document`; index and retrieval adapters belong to `rag`, using shared database +and model facilities. Defaults may be referenced by `rag`, while component schemas are validated by their owner. + +Reuse Source and Artifact plugin registration and existing management/read conventions. The current generation +model must be extended for explicit `rag` creation, domain detail storage, and target-specific work: an empty `rag` +is a managed object, not the output of Source consumption. Do not create a fake input Source to schedule its creation +or claim the generic plugin manifest alone supplies these capabilities. Existing system-generated management +provenance may still be recorded without triggering document processing. + +A knowledge-base application service coordinates the use case through registered family capabilities. It is not +a fourth domain plugin. Each writer owns its records and participates in the caller's shared database transaction; +plugins do not write each other's private tables or commit independently. This uses one deployment database, not +a distributed transaction between plugin services. The document parser cannot choose the target `rag`. + +## 3. Parsing and chunk storage + +Markdown processing uses `markdown-it-py`, retaining headings, paragraphs, lists, code, tables, and links. +Map parser locations back to original UTF-8 bytes; do not fabricate inline precision from block-level line ranges. +RapidOCR with ONNX Runtime processes standalone images with pinned model identities, image-size limits, and +coordinate mapping back to the original image after preprocessing. Preserve actual OCR text, confidence, and +regions. Distinguish unsupported input, invalid encoding, damaged images, no recognized text, missing models, +and timeouts. Do not use generation models to fill in or rewrite OCR output. + +Both paths produce validated blocks, sections, and source locators for a configurable heading/paragraph/length +chunker. Preserve ordering, overlap/continuation, neighboring chunks, and potentially multiple source spans or +image regions. A locator describes actual evidence; OCR confidence is an engine score, not a promised accuracy. + +| Storage | Proposed representation | +| --- | --- | +| Existing Artifact records and heads | One bounded manifest per document revision: title/summary, original Source reference, configuration identifiers, schema version, chunk count, and collection digest | +| Document detail records | One row per chunk keyed by `(scope, document_id, revision, chunk_id)`, plus section/block structure and evidence/edit metadata | +| Membership and target state | `rag` ownership, logical document key, desired input/configuration, and lifecycle/concurrency generations | +| Retrieval projections | Chunk-level full-text/vector entries and exact revision/profile/generation mappings | +| Processing records | Durable target requests, stage/results, retries, leases, and recoverable indexing/cleanup work | + +Reuse Artifact, head, lineage, tag, and processing facilities where their semantics match. Do not add duplicate +knowledge-base/document/revision master tables or mix document rows into family-specific Topic Memory chunk tables. +Physical names and backend-specific auxiliary indexes are implementation decisions. + +Each revision initially stores a **complete chunk snapshot**. A 100-chunk document has one manifest and 100 detail +rows; editing one chunk creates another manifest and a complete 100-row snapshot. Validate counts, unique ordering, +structure references, and a digest covering effective text, order, and evidence mappings. Batched staging remains +invisible until the complete revision is committed. This deliberately accepts storage amplification for simpler +revision reads and recovery; shared chunk bodies across revisions are deferred. + +The main Artifact content must not contain an unbounded full-text/chunk/vector array. Search accesses chunk indexes +directly, then batch-loads exact hits and same-revision neighbors. Generic Artifact reads return the manifest; +detail pagination fixes revision, view, and ordering in the cursor. Distinguish original parsed evidence from +effective edited chunks. Overlapping chunks cannot simply be concatenated into an edited full-document export. + +## 4. Targeted asynchronous work and publication + +An import request fixes the Scope, target `rag`, exact SourceRef, logical document identity, processing configuration +snapshot, and input/request generation. Accepting or reusing a Source and recording target work must be atomic. +Source journal replay alone is insufficient: reuse in another `rag`, retries, and configuration rebuilds may append +no Source entry and must explicitly request processing. + +Reuse Scope/binding supervision, leases, timeouts, and execution fences. Workers claim persisted target work; +they do not broadcast every Source to every `rag`. The stages are parse/OCR, chunk/content commit, index build, +and publication. Each work item follows these transitions, with bounded retry policy: + +```text +queued -> running -> succeeded + +--> retry_wait -> queued + +--> failed +queued / running / retry_wait -> cancelled or superseded +failed -> queued through an authorized explicit retry +``` + +Expose stage, failure reason, attempt, and both latest-content and searchable revision. A first failure may have +no document Artifact yet. Retry the failed durable stage without duplicating content revisions or publication. +Replaying an idempotency key with a different request digest is a conflict. + +| Boundary | Atomic records / required checks | +| --- | --- | +| Snapshot preparation | Persist bytes before acceptance; failed acceptance may leave an unreferenced snapshot for cleanup | +| Import acceptance | Source acceptance/reuse, validated target request, and durable scheduling intent | +| Content commit | Complete manifest/details, provenance, validated membership, content receipt, and index work; manual edits also create their system Source here | +| Index publication | Verify complete indexes, exact content target, active configuration, execution ownership, and lifecycle; switch the searchable selection and visibility generation | +| Source revocation | Persist lifecycle tombstone, advance visibility generation, and record cascading cleanup before acknowledging deletion | + +Run OCR, embeddings, DDL, and bulk index construction outside these short transactions. Every commit rechecks +registration/lease fences, target state, and input/configuration/deletion generations. A newer edit or import +supersedes old publication work. Durable work records are authoritative; process-local notifications only wake workers. + +Content head and searchable revision are distinct. Index failure preserves the previous published revision while +showing the new content and error. A `rag` rebuild uses a new generation and catches up accepted changes to a verified +cutover watermark before switching; a partially built generation cannot replace the active one. Rebuilding one +knowledge base cannot switch another's generation. Filesystem/database backup and restore must verify referenced +snapshots and index consistency before serving restored retrieval. + +## 5. Manual editing, reprocessing, and deletion + +Initially allow replacement of one existing chunk's text, guarded by the document head ETag. Do not expose chunk +insertion, deletion, merging, or reordering. Reject oversized edits rather than silently rechunking. Editing one +chunk does not silently edit overlapping text in another chunk. + +Follow Artifact management's provenance pattern: in the content transaction create a system Content Source with +`role=lineage_only` and `operation=artifact_replace`, then commit the new document revision and index work. Record +the base revision, edit, actor/reason, and exact target. This Source is not parsed again. Explicitly preserve the +original input Source dependency as well as the edit Source and base revision; generic replacement provenance +must not be assumed to retain the root input automatically. + +Manual replacement preserves logical chunk IDs, but citations always include revision. Reparse/rechunk generates +new chunk IDs; ordinal position is not identity. Edited results carry `origin=manual_edit` and `verbatim=false`: +their original locator is supporting evidence, not a claim that the edited words appear there. + +Updates refresh full-text entries, vector mappings, publication selection, and visibility-sensitive caches. +Embedding computation may be reused only when the complete actual input and model/profile identity match; +even then, new revision addresses must be indexed. Changing only embedding/index configuration preserves edited +content. Reprocessing manually edited content requires explicit `manual_edits_policy=discard`, otherwise a conflict. +Editing while a Source replacement/reparse is pending is rejected; editing committed content still being indexed +is allowed and supersedes older index work. Check these conditions atomically with target state. + +Deleting an original Source is a Scope-authorized operation that revokes every dependent document revision, +including manually edited revisions and dependencies in other `rag` Artifacts in that Scope. Membership references +do not prevent deletion; `rag` configuration remains. Revocation immediately gates search, caches, original reads, +and ordinary/historical Artifact and chunk reads, while physical cleanup is asynchronous and retryable. Returning +an in-flight result requires a visibility recheck; responses already delivered cannot be recalled. + +Cleanup includes dependent text, OCR/parse caches, indexes, and edit-Source/audit payloads containing that text. +Minimal non-content receipts may remain. An original Source's payload is never rewritten by ordinary editing; +explicit erasure follows its separate lifecycle. Removing one knowledge base does not delete a shared Source. +Deleting an old Source does not revoke revisions derived solely from its replacement, and a revoked old revision +cannot remain as a search fallback. Never delete the user's original file; reclaim managed snapshots only when +no live reference needs them. Late workers must fail the same deletion fence used by revocation. + +## 6. Retrieval and public interfaces + +Queries select complete `rag` references, in one Scope or across authorized Scopes. A Scope alone must not silently +select the first or all knowledge bases. Authorize every target and apply membership, metadata, lifecycle, +published-revision, and generation filters within each full-text/vector channel. Do not retrieve Scope-wide top-k +and filter afterward. If a backend cannot apply eligible-candidate filtering with ANN, use a verified filtered +exact-vector path rather than silently changing the retrieval contract. + +Use bounded candidate counts and deterministic rank fusion. Different embedding profiles require compatible +query embeddings; incompatible raw scores cannot be compared across knowledge bases. Deduplication preserves +distinct provenance. Return text, Scope/`rag`, document/revision/chunk, SourceRef, locator, edit markers, and actual +index profile/generation. Report per-target failures separately from no matches; all targets failing is a failure. +Parser, chunker, retrieval strategy, and optional reranking hooks must preserve these budgets and evidence contracts. + +Reuse generic Artifact create/read/replace/revision/tag shapes, complete references, pagination, errors, and +conditional writes. Add domain capabilities for targeted import, task inspection/retry, revision-pinned chunk +reads, chunk editing, retrieval, and Source revocation. Do not expose unrestricted generic document replacement +that can bypass provenance and ownership validation. Keep HTTP, Python client, and necessary MCP capabilities +consistent, with explicit knowledge-base context selection and unchanged Memory retrieval defaults. + +Final URLs and schemas belong in `openapi/powercontext.yaml` during implementation, followed by generated clients +and contract checks. This RFC specifies operation semantics rather than presenting unimplemented curl examples. +New families and detail tables require versioned migrations on all three backends; existing Sources and Artifact +families retain their contracts and are not automatically converted or enrolled in document processing. + +## 7. Acceptance and delivery + +Use Markdown from a pinned `oceanbase/oceanbase` commit and standalone OCR fixtures with checked text/locators. +On SQLite, SeekDB, and OceanBase, verify: + +- Multiple empty knowledge bases per Scope, automatic document membership, exact citations, single-base filtering, + and explicitly authorized same-Scope/cross-Scope queries. +- Existing-Source reuse and idempotent retries, first-import failure without a document, process restart, atomic + content/membership/work commit, and failed indexing with an old searchable revision. +- Real RapidOCR execution, malformed/unsupported input and no-text outcomes, preserved Markdown image references, + and full-text/vector retrieval over document chunks without whole-document JSON scans. +- Manual edit provenance, complete snapshots, revision-pinned pagination, updated full-text/vector mappings, + reparse conflicts, stale-worker rejection, and generation cutover during concurrent updates. +- Source revocation across shared dependencies, historical/cache/original-read enforcement, retryable cleanup, + and preservation of unrelated documents, replacement-Source revisions, and `rag` configurations. + +Use existing issues for delivery: #2441 covers foundations/ingestion, #2442 processing/content/index lifecycle, +#2443 retrieval/interfaces, and #2444 operational visibility and cross-backend acceptance. The implementation can +use one integration branch and PR with these four review stages. This RFC PR completes none of those implementation +issues. Publish supported formats, model versions, resource limits, and recovery instructions with implementation; +do not infer production capacity from functional fixtures. + +# Drawbacks + +Complete snapshots amplify storage and write cost even for a one-chunk edit. Separating content and searchable +revisions complicates reads and diagnostics. Dedicated consumer restrictions, target work, family writers, and +revocation need framework integration beyond a plugin declaration. Three backends add migration and index testing +cost. RapidOCR model packaging and platform compatibility also require explicit maintenance. + +# Rationale and alternatives + +- **A Scope per knowledge base:** provides existing isolation but couples collection organization to authorization + and project identity. Multiple `rag` Artifacts keep those concerns separate; use separate Scopes when isolation is required. +- **Chunks stored in mutable Sources:** mixes original evidence with derived content and conflicts with Source immutability. +- **One Artifact per chunk:** turns a whole-document update into many independent Artifact lifecycles and obscures atomic revisions. +- **All chunks in one Artifact JSON field:** simplifies writes but makes passage reads and indexing depend on large payloads. +- **Independent knowledge-base master tables:** duplicate existing Artifact identity, version, and management facilities. +- **Source-journal-only generation:** cannot reliably express empty `rag` creation or work triggered by existing-Source reuse. + +The selected design preserves whole-document identity while giving chunks efficient physical storage and explicit +publication. Doing nothing leaves applications to assemble inconsistent ingestion, provenance, and deletion workflows. + +# Prior art + +This proposal builds on the repository's [Source plugin design](2012-source-plugin-system.md), +[Artifact plugin design](2175-artifact-plugin-system.md), [Source model](1400_source_definition_and_observation_model.md), +[Artifact processing supervisor](1515_artifact_processing_supervisor.md), +[Source/Artifact API](1437_source_artifact_rest_api.md), and [Topic Memory](1417_topic_memory.md). +It reuses their extension, provenance, scheduling, and read boundaries while adding explicit collection management +and document-specific storage/publication. Topic Memory's family-specific detail/index schema is not a shared document schema. + +# Unresolved questions + +The following must be fixed and tested in the implementing changes; they do not defer identity, atomicity, +consumer restrictions, or revocation semantics: + +- Exact family capability/writer extensions, API schemas, migration names, and backend index layouts. +- Limits for snapshots, decoded image pixels, manifests, chunks, pages, worker concurrency, timeouts, and retries. +- Pinned RapidOCR/ONNX/model versions, supported image formats/platforms, and default chunk/embedding profiles. +- Historical revision retention, staging/snapshot garbage collection, and resulting expired-reference responses. + +Full edited-document export needs an explicit overlap and edit reconciliation contract. Independent per-`rag` ACLs, +cross-deployment federation, and shared document ownership require separate design work rather than implicit support. + +# Future possibilities + +Additional parsers, storage providers, automatic collection, alternative chunkers, rerankers, and bounded agentic +retrieval can use the declared component boundaries. Measured storage pressure may justify shared immutable chunk +bodies across revisions. These extensions must preserve exact evidence, target isolation, and publication/deletion +semantics; they are not prerequisites for the initial knowledge-base workflow. diff --git a/docs/zh/rfcs/0000-rag-knowledge-base.md b/docs/zh/rfcs/0000-rag-knowledge-base.md new file mode 100644 index 0000000000..bd08935875 --- /dev/null +++ b/docs/zh/rfcs/0000-rag-knowledge-base.md @@ -0,0 +1,251 @@ +--- +title: "RFC 0000:基于 rag Artifact 的文档知识库" +description: "通过插件实现文档知识库,保留不可变 Source、分块版本、混合检索与可恢复的后台处理。" +--- + +- Proposal Name: `rag_knowledge_base` +- Start Date: 2026-11-10 +- RFC PR: [#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) +- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) + +# 概述 + +通过一个文档 Source 插件和 `document`、`rag` 两种 Artifact family 提供文档知识库。一个 Scope 内允许用户创建多个 +`rag` Artifact。用户向指定 `rag` 导入文件,后台解析不可变输入,生成代表整篇文档、分行保存 chunks 的 document Artifact, +自动关联知识库,再发布全文/向量索引。本文描述设计目标,不表示接口已经发布。 + +# 动机 + +业务描述和任务 SOP 需要带精确证据的片段检索,以及显式更新和删除能力。提取的记忆可以补充这一场景,但不能保留全部文档内容。 +知识库必须区分原始输入、处理后的内容和可检索版本,避免处理失败破坏已有结果,也避免把人工纠正伪装成原始证据。 + +复用 PowerContext 的 Source 定义、Artifact 管理、插件注册、Scope 授权、处理监督和持久化设施,补充其中尚缺的文档专用契约, +不另建平行的知识库对象体系或通用工作流引擎。 + +# 使用层说明 + +Scope 继续代表项目或工作空间,并作为首期授权边界。知识库是 Scope 内的 `rag` Artifact,拥有独立名称和处理/检索配置。 +知识库改名或删除不会改变 Scope。一个 Scope 内的不同知识库不构成独立的保密边界。 + +例如,团队在同一 Scope 中创建“产品文档”和“运维 SOP”: + +1. 通过 Artifact 管理创建两个空 `rag`,无需先导入文档。 +2. 向“产品文档”导入 Markdown,向“运维 SOP”导入独立的文字图片。 +3. 获取持久导入回执,查看解析、索引和失败状态。 +4. 检索单个知识库,或显式选择两个库联合检索。处理后文档自动关联知识库,索引发布后才能检索,无需手动挂载 document。 +5. 替换原文件或编辑已有 chunk,生成新 document revision;索引就绪后新内容参与检索。更新失败时保留旧发布版本,除非它已被撤销或移除。 + +首期支持 Markdown 和独立导入的图片,OCR 使用 RapidOCR + ONNX Runtime。Markdown 图片仅保留引用,不抓取或识别引用目标。 +SQLite、SeekDB、OceanBase 均须支持完整功能链路;一个部署使用其中一种后端。 + +普通 TXT、PDF、Office、自动同步、生产级 rerank、agentic 检索、完整管理界面和几万篇文档的规模评测不作为首期验收条件。 +但任务状态和恢复 API 必须能支撑后续界面。根据检索结果回答问题仍由应用负责。 + +# 技术说明 + +## 1. 身份、归属与溯源 + +```text +Scope + +-- rag K1 -- 成员关系 --> document D1 -- revisions --> chunks + +-- rag K2 -- 成员关系 --> document D2 -- revisions --> chunks + ^ +不可变文档 Source ---------------+ 内容溯源 +``` + +| 对象 | 身份与职责 | +| --- | --- | +| `rag` Artifact | 用户创建的配置与集合身份;成员变化和处理进度不生成配置 revision | +| 文档 Source | 不可变原始输入描述:原路径、受管理快照引用、摘要、媒体类型和采集元数据 | +| `document` Artifact | 一篇完整逻辑文档,ID 稳定,内容 revision 递增;首期唯一归属一个 `rag` | +| Chunk | document revision 内部的内容和检索单元,不是 Source 或独立 Artifact | +| 索引 generation | 以 `rag` 为范围的索引配置/构建,与内容 revision、插件注册代次分离 | + +逻辑文档身份为 `(scope, rag, source_namespace, external_key)`。同一身份再次导入更新原 document;同路径导入另一 `rag` +产生独立 document,不能按内容摘要合并逻辑身份。一个不可变 Source 可显式复用于同 Scope 的多个知识库,但不因此建立跨 Scope +Source 身份或共享 document 归属。 + +Source lineage、`rag` 成员关系和可检索 revision 选择是三种不同关系,不能用标签代替归属。原路径用于溯源,读取使用采集时的 +不可变快照,而非路径现在指向的文件。原始 Markdown 字节和图片保存在 OpenDAL 管理的本地目录,适当复用现有 OpenDAL/`opendalfs` 集成。 + +定义专用文档 Source 类型,暂称 `knowledge-document-input`,仅允许 document 处理链路直接消费。在输入选择、执行和提交校验中 +落实限制,不仅靠命名约定;不能自动将其暴露到其他 Artifact family 消费的通用证据流。解析结果、OCR 文字、chunks、索引指针和 +任务进度不得回写 Source payload。 + +## 2. 插件职责与框架适配 + +| 逻辑插件 | 负责的行为 | +| --- | --- | +| 文档 Source | 文件校验、不可变快照、Source 接受、授权后的原文读取 | +| `document` Artifact | 解析、OCR、切块、内容版本、chunk 读取、人工编辑和证据映射 | +| `rag` Artifact | 配置、成员关系、索引 generation、发布、混合检索和显式多库查询 | + +这是三个逻辑插件,不要求三个进程或独立安装包。Parser/OCR/chunker 是 document 内的可替换组件;索引和检索适配归 rag, +使用共享数据库和模型设施。rag 可以引用默认配置,组件 schema 由其所属能力校验。 + +复用 Source、Artifact 插件注册及现有管理/读取约定。现有生成模型仍需扩展显式 rag 创建、领域明细存储和定向任务能力: +空 rag 是管理对象,不是消费 Source 的生成结果。不能伪造输入 Source 来触发建库,也不能声称仅配置通用插件声明就已满足全部能力。 +仍可记录现有系统生成的管理溯源,但不触发文档处理。 + +知识库应用服务通过注册的 family 能力协调这些操作,不是第四个领域插件。各 writer 只管理本领域记录,并参与调用方共享数据库事务; +插件不能写其他插件的私有表或独立提交。首期使用同一部署数据库,不做插件服务间的分布式事务。document parser 无权决定目标 rag。 + +## 3. 解析与 chunk 存储 + +Markdown 使用 `markdown-it-py` 处理,保留标题、段落、列表、代码、表格和链接。将解析位置映射回原始 UTF-8 字节,不能用块级行号 +伪造行内精确位置。RapidOCR + ONNX Runtime 处理独立图片,固定模型身份、限制图片大小,并将预处理后的坐标映射回原图。 +保留真实 OCR 文字、置信度和区域;区分不支持的输入、非法编码、坏图、无识别文字、模型缺失和超时,不用生成模型补写或改写 OCR 输出。 + +两条路径都输出经过校验的 blocks、sections 和原文定位,交给可配置的标题/段落/长度切块策略。保留顺序、重叠/续块关系、邻接信息, +以及可能包含多个原文跨度或图片区域的定位。定位必须对应真实证据;OCR 置信度是引擎分数,不是准确率承诺。 + +| 存储 | 建议表示 | +| --- | --- | +| 现有 Artifact 记录与 heads | 每个 document revision 一条有界 manifest:标题/摘要、原始 Source 引用、配置标识、schema 版本、chunk 数量和集合摘要 | +| 文档明细 | 每 chunk 一行,以 `(scope, document_id, revision, chunk_id)` 为键,配套章节/block 结构和证据/编辑元数据 | +| 成员与目标状态 | rag 归属、逻辑文档键、目标输入/配置,以及生命周期和并发代次 | +| 检索投影 | chunk 级全文/向量条目及精确 revision/profile/generation 映射 | +| 处理记录 | 持久目标请求、阶段/结果、重试、租约及可恢复的索引/清理工作 | + +在语义匹配时复用 Artifact、head、lineage、tag 和处理设施。不新增重复的知识库/document/revision 主表,也不将文档数据混入 +Topic Memory 专属 chunk 表。物理表名和各后端辅助索引在实现时确定。 + +首期每个 revision 保存**完整 chunk 快照**。100 块的文档保存一条 manifest 和 100 行明细;编辑一个块后再保存一条 manifest +和完整 100 行快照。校验数量、唯一顺序、结构引用,以及覆盖有效文本、顺序和证据映射的摘要。分批暂存数据在完整 revision 提交前不可见。 +这一选择接受存储放大,以简化版本读取和恢复;跨 revision 共享 chunk 正文留待后续。 + +Artifact 主体不能保存无界的全文/chunk/向量数组。检索直接访问 chunk 索引,再批量读取精确命中和同版本邻接块。通用 Artifact +读取返回 manifest;明细分页游标固定 revision、视图和顺序。原始解析证据与编辑后的有效 chunks 分开读取,不能直接拼接重叠 chunks +来导出编辑后的整篇文档。 + +## 4. 定向异步任务与发布 + +导入请求固定 Scope、目标 rag、精确 SourceRef、逻辑文档身份、处理配置快照和输入/请求代次。接受或复用 Source 与记录目标工作 +必须原子完成。仅依赖 Source journal 重放不够:已有 Source 导入另一 rag、重试和配置重建可能不新增 Source,必须显式请求处理。 + +复用 Scope/binding 的监督、租约、超时和执行栅栏。Worker 领取持久目标工作,不向所有 rag 广播 Scope 中的每个 Source。 +阶段包括解析/OCR、切块与内容提交、索引构建、发布。工作项遵循以下状态转换,并使用有上限的重试策略: + +```text +queued -> running -> succeeded + +--> retry_wait -> queued + +--> failed +queued / running / retry_wait -> cancelled 或 superseded +failed -> 经授权的显式重试 -> queued +``` + +暴露阶段、失败原因、attempt,以及最新内容和可检索 revision。首次失败时可以尚无 document Artifact。重试失败的持久阶段, +不重复生成内容版本或发布。同一幂等键携带不同请求摘要时返回冲突。 + +| 边界 | 原子记录/必要校验 | +| --- | --- | +| 快照准备 | 接受前保存字节;接受失败可能留下待清理的无引用快照 | +| 导入接受 | Source 接受/复用、已验证的目标请求和持久调度意图 | +| 内容提交 | 完整 manifest/明细、溯源、已验证的成员关系、内容回执和索引工作;人工编辑在此创建系统 Source | +| 索引发布 | 校验完整索引、精确内容目标、生效配置、执行资格和生命周期;切换可检索选择及可见代次 | +| Source 撤销 | 确认删除前持久化生命周期 tombstone、推进可见代次并记录级联清理 | + +OCR、embedding、DDL 和批量索引构建都在上述短事务外执行。每次提交重新校验注册/租约栅栏、目标状态及输入/配置/删除代次。 +新的编辑或导入使旧发布任务失效。持久工作记录是恢复依据,进程内通知仅加速唤醒。 + +内容 head 与可检索 revision 分离。索引失败时保留旧发布版本,同时展示新内容和错误。rag 重建使用新 generation,在切换前追平已接受 +变更到经验证的水位,不能用部分构建替换当前 generation。重建一个知识库不得切换其他库的 generation。文件系统/数据库备份恢复后, +应验证被引用快照和索引一致性,再开放恢复后的检索。 + +## 5. 人工编辑、重处理与删除 + +首期只允许替换一个已有 chunk 的文字,以 document head ETag 做并发控制;不开放 chunk 增删、合并或重排。超长编辑明确拒绝, +不静默重切块。编辑一个 chunk 不自动修改其他 chunk 中的重叠文字。 + +沿用 Artifact 管理的溯源模式:在内容事务中创建 `role=lineage_only`、`operation=artifact_replace` 的系统 Content Source, +再提交新 document revision 和索引工作。记录 base revision、修改内容、操作者/原因及精确目标。该 Source 不再次进入解析。 +除编辑 Source 和 base revision 外,显式保留原始输入 Source 依赖,不能假设通用替换溯源会自动保留根输入。 + +人工替换保留逻辑 chunk ID,但引用始终包含 revision。重新解析/切块生成新 chunk ID,序号不代表身份。编辑后的结果标记 +`origin=manual_edit` 和 `verbatim=false`;原始定位是修改依据,不表示修改后的文字逐字出现在原文中。 + +更新同步全文条目、向量映射、发布选择及受可见性约束的缓存。只有完整实际输入和模型/profile 身份一致时才可复用 embedding 计算, +即使复用也必须索引新 revision 地址。仅修改 embedding/索引配置保留人工编辑内容。重处理含人工修改的内容必须显式指定 +`manual_edits_policy=discard`,否则冲突。Source 替换/重解析尚未提交时拒绝编辑;已提交内容仍在索引时允许继续编辑,并使旧索引 +任务失效。这些条件必须和目标状态一起原子校验。 + +删除原始 Source 是 Scope 授权下的操作,撤销所有依赖 document revision,包括人工编辑版本及同 Scope 其他 rag 中的依赖。 +成员引用不阻止删除,rag 配置保留。撤销立即约束检索、缓存、原文读取及普通/历史 Artifact 和 chunk 读取,物理清理异步执行并可重试。 +在途结果返回前重新校验可见性;已经发送的响应无法收回。 + +清理范围包含依赖正文、OCR/解析缓存、索引,以及携带正文的编辑 Source/审计 payload,可保留最小的无正文回执。 +普通编辑不改写原始 Source payload,显式擦除使用独立生命周期。移除一个知识库不删除共享 Source;删除旧 Source 不撤销仅依赖其替代 +Source 的 revision,也不能保留被撤销旧版作为检索兜底。不删除用户原文件,受管理快照仅在没有存活引用时回收。 +迟到 Worker 必须受与撤销相同的删除栅栏约束。 + +## 6. 检索与公开接口 + +查询显式选择完整 rag 引用,可位于同一 Scope 或多个已授权 Scope。不能仅凭 Scope 默认选第一个或全部知识库。 +逐目标授权,在全文/向量通道内落实成员、元数据、生命周期、已发布 revision 和 generation 过滤,不能先取整个 Scope 的 top-k 再过滤。 +后端 ANN 无法满足合格候选集合过滤时,使用经过验证的过滤集合内精确向量检索,不静默改变检索契约。 + +限制候选数量并采用确定性的排名融合。不同 embedding profile 使用兼容的查询向量,不能跨库比较不兼容的原始分数。 +去重保留不同来源证据。结果返回正文、Scope/rag、document/revision/chunk、SourceRef、定位、编辑标记及实际索引 profile/generation。 +逐目标失败与无命中分开报告,全部目标失败时返回失败。Parser、chunker、检索策略和可选 rerank 扩展均须保持预算与证据契约。 + +复用通用 Artifact 创建/读取/替换/revision/tag 的形状、完整引用、分页、错误和条件写入约定,新增定向导入、任务查看/重试、 +固定 revision 的 chunk 读取、chunk 编辑、检索和 Source 撤销等领域能力。不开放能绕过溯源和归属校验的任意 document 替换。 +HTTP、Python client 和必要 MCP 能力保持一致,知识库上下文显式选择,现有 Memory 检索默认行为不变。 + +最终 URL 和 schema 在实现时写入 `openapi/powercontext.yaml`,随后生成客户端并运行契约检查。本文确定操作语义,不给出尚未实现的 +curl 示例。新 family 和明细表通过三个后端的版本化迁移引入;既有 Source 和 Artifact family 保持原契约,不自动转换或加入文档处理。 + +## 7. 验收与交付 + +使用 `oceanbase/oceanbase` 固定 commit 的 Markdown,以及文字/定位已核验的独立 OCR 图片。SQLite、SeekDB、OceanBase 均验证: + +- 同 Scope 多个空知识库、自动文档归属、精确引用、单库过滤,以及显式授权的同 Scope/跨 Scope 查询。 +- 已有 Source 复用、幂等重试、无 document 的首次失败、进程重启、内容/成员/工作原子提交,以及索引失败时旧版本可检索。 +- 真实 RapidOCR、非法/不支持输入和无文字结果、Markdown 图片引用保留,以及不扫描整篇 JSON 的 chunk 全文/向量检索。 +- 人工编辑溯源、完整快照、固定 revision 分页、全文/向量映射更新、重解析冲突、迟到 Worker 拒绝,以及并发更新下的 generation 切换。 +- 共享依赖上的 Source 撤销,历史/缓存/原文读取校验,可重试清理,以及无关文档、替代 Source 版本和 rag 配置的保留。 + +沿用现有 Issue:#2441 负责基础与导入,#2442 负责处理/内容/索引生命周期,#2443 负责检索和接口,#2444 负责运行可见性与三后端验收。 +实现可采用一个集成分支和 PR,按这四个阶段评审。本 RFC PR 不完成这些实施 Issue。随实现发布支持格式、模型版本、资源限制和恢复说明, +不从功能样本推断生产容量。 + +# 缺点 + +完整快照使单块编辑也增加存储和写入成本。区分内容版本与检索版本增加读取和诊断复杂度。专用消费限制、定向任务、family writer 和 +撤销机制需要超出插件声明的框架适配。三后端增加迁移和索引测试成本,RapidOCR 模型分发及平台兼容性也需要明确维护。 + +# 设计理由与替代方案 + +- **每个知识库一个 Scope:** 可以复用现有隔离,但会把集合组织绑定到授权和项目身份。多 rag 将这些职责分离,需要隔离时仍使用不同 Scope。 +- **将 chunks 存在可变 Source 中:** 混淆原始证据和派生内容,违反 Source 不可变原则。 +- **每个 chunk 一个 Artifact:** 将整篇文档更新拆成多个独立 Artifact 生命周期,难以表达原子文档版本。 +- **全部 chunks 放在 Artifact JSON 中:** 写入简单,但片段读取和索引依赖大 payload。 +- **独立知识库主表:** 重复已有 Artifact 身份、版本和管理设施。 +- **只靠 Source journal 生成:** 无法可靠表达空 rag 创建或已有 Source 复用引发的工作。 + +选定模型保留整篇文档身份,同时为 chunks 提供适合检索的物理存储和明确发布语义。不提供这一能力,会使各应用自行拼装不一致的导入、 +溯源和删除流程。 + +# 既有设计 + +本提案基于仓库的 [Source 插件设计](2012-source-plugin-system.md)、[Artifact 插件设计](2175-artifact-plugin-system.md)、 +[Source 模型](1400_source_definition_and_observation_model.md)、[Artifact 处理监督](1515_artifact_processing_supervisor.md)、 +[Source/Artifact API](1437_source_artifact_rest_api.md) 和 [Topic Memory](1417_topic_memory.md)。复用其扩展、溯源、调度和读取边界, +增加显式集合管理和文档专属存储/发布。Topic Memory 的专属明细/索引 schema 不作为共享文档 schema。 + +# 待解决问题 + +以下内容须在对应实现中固定并测试,不延后身份、原子性、消费限制和撤销语义: + +- 精确的 family 能力/writer 扩展、API schema、迁移名称和后端索引布局。 +- 快照、解码图片像素、manifest、chunk、分页、Worker 并发、超时和重试限制。 +- 固定的 RapidOCR/ONNX/模型版本、支持的图片格式/平台,以及默认切块/embedding profiles。 +- 历史 revision 保留期、暂存/快照垃圾回收及过期引用响应。 + +完整编辑文档导出需要明确重叠和编辑合并契约。独立 rag ACL、跨部署联合查询和共享 document 归属需要单独设计,不隐式提供。 + +# 后续可能性 + +更多解析器、存储后端、自动采集、切块策略、rerank 和受限 agentic 检索可以复用组件边界。测量到实际存储压力后,可考虑跨 revision +共享不可变 chunk 正文。这些扩展必须保留精确证据、目标隔离、发布与删除语义,不作为首期知识库流程的前置条件。 From c59b6098833c0fe6809e23fdce980e90062e0dd3 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Tue, 10 Nov 2026 10:31:29 +0800 Subject: [PATCH 02/13] docs(rfc): assign RFC 2570 after opening PR --- ...{0000-rag-knowledge-base.md => 2570-rag-knowledge-base.md} | 4 ++-- ...{0000-rag-knowledge-base.md => 2570-rag-knowledge-base.md} | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename docs/en/rfcs/{0000-rag-knowledge-base.md => 2570-rag-knowledge-base.md} (99%) rename docs/zh/rfcs/{0000-rag-knowledge-base.md => 2570-rag-knowledge-base.md} (99%) diff --git a/docs/en/rfcs/0000-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md similarity index 99% rename from docs/en/rfcs/0000-rag-knowledge-base.md rename to docs/en/rfcs/2570-rag-knowledge-base.md index 23cf559ae7..7377ef783a 100644 --- a/docs/en/rfcs/0000-rag-knowledge-base.md +++ b/docs/en/rfcs/2570-rag-knowledge-base.md @@ -1,11 +1,11 @@ --- -title: "RFC 0000: Document knowledge bases with rag Artifacts" +title: "RFC 2570: Document knowledge bases with rag Artifacts" description: "A proposal for plugin-based knowledge bases with immutable document Sources, versioned chunks, hybrid retrieval, and recoverable processing." --- - Proposal Name: `rag_knowledge_base` - Start Date: 2026-11-10 -- RFC PR: [#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) - Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) - Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) diff --git a/docs/zh/rfcs/0000-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md similarity index 99% rename from docs/zh/rfcs/0000-rag-knowledge-base.md rename to docs/zh/rfcs/2570-rag-knowledge-base.md index bd08935875..602ebc29ec 100644 --- a/docs/zh/rfcs/0000-rag-knowledge-base.md +++ b/docs/zh/rfcs/2570-rag-knowledge-base.md @@ -1,11 +1,11 @@ --- -title: "RFC 0000:基于 rag Artifact 的文档知识库" +title: "RFC 2570:基于 rag Artifact 的文档知识库" description: "通过插件实现文档知识库,保留不可变 Source、分块版本、混合检索与可恢复的后台处理。" --- - Proposal Name: `rag_knowledge_base` - Start Date: 2026-11-10 -- RFC PR: [#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) - Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) - Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) From bb578568a8d6ee45ede522cebba6797cf440f451 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Tue, 10 Nov 2026 16:05:47 +0800 Subject: [PATCH 03/13] docs(rfc): define rag APIs, persistence, and soft deletion --- docs/en/rfcs/2570-rag-knowledge-base.md | 319 ++++++++++++++++++++++-- docs/zh/rfcs/2570-rag-knowledge-base.md | 272 ++++++++++++++++++-- 2 files changed, 549 insertions(+), 42 deletions(-) diff --git a/docs/en/rfcs/2570-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md index 7377ef783a..6cc53c85ed 100644 --- a/docs/en/rfcs/2570-rag-knowledge-base.md +++ b/docs/en/rfcs/2570-rag-knowledge-base.md @@ -128,11 +128,12 @@ image regions. A locator describes actual evidence; OCR confidence is an engine | Document detail records | One row per chunk keyed by `(scope, document_id, revision, chunk_id)`, plus section/block structure and evidence/edit metadata | | Membership and target state | `rag` ownership, logical document key, desired input/configuration, and lifecycle/concurrency generations | | Retrieval projections | Chunk-level full-text/vector entries and exact revision/profile/generation mappings | -| Processing records | Durable target requests, stage/results, retries, leases, and recoverable indexing/cleanup work | +| Processing records | Durable target requests, stage/results, retries, leases, and recoverable indexing work and deletion receipts | Reuse Artifact, head, lineage, tag, and processing facilities where their semantics match. Do not add duplicate knowledge-base/document/revision master tables or mix document rows into family-specific Topic Memory chunk tables. -Physical names and backend-specific auxiliary indexes are implementation decisions. +The proposed schema below fixes ownership, keys, and minimum fields. Backend-specific DDL and auxiliary indexes +are finalized through migrations, not runtime table creation. Each revision initially stores a **complete chunk snapshot**. A 100-chunk document has one manifest and 100 detail rows; editing one chunk creates another manifest and a complete 100-row snapshot. Validate counts, unique ordering, @@ -145,6 +146,88 @@ directly, then batch-loads exact hits and same-revision neighbors. Generic Artif detail pagination fixes revision, view, and ordering in the cursor. Distinguish original parsed evidence from effective edited chunks. Overlapping chunks cannot simply be concatenated into an edited full-document export. +### 3.1. Existing tables to reuse + +| Existing table / facility | Use and required adaptation | +| --- | --- | +| `pc_sources`, `pc_source_journal_heads` | Keep canonical payloads and journal order immutable; reference original snapshots, not derived chunks | +| `pc_artifacts`, `pc_artifact_heads` | Store rag configuration and document manifests/revisions; keep family in every Artifact key; head is not a retrieval-publication pointer | +| `pc_artifact_lineage_sources`, `pc_artifact_source_locators` | Preserve root input and edit Sources; add/verify reverse lookup on `(scope_id, source_type, source_id)` | +| `pc_artifact_lineage_artifacts` and tags | Exact base-revision evidence and tagging, not rag membership | +| `pc_artifact_processing_intents`, leases, binding states | Reuse wakeup, ownership, and registration fences; store per-document work separately | +| `pc_scope_settings` | Reserve a system-owned Source-visibility epoch, advanced atomically on Source deletion; not user-editable | + +Do not reuse `pc_artifact_publications` for searchable revisions: it represents cross-Scope publication. Generic +search state is keyed by Scope/family and cannot select independent generations for two rags without extension. +Reuse vector-space definitions and adapter code where applicable, but keep rag publication explicit. The generic +head's `searchable_text` is not the passage index. + +### 3.2. Proposed relational schema + +These are proposed names, not installed schema. The baseline has seven domain tables, one shared Source lifecycle +table, and one chunk-index projection. It adds no duplicate Source/Artifact/revision master, separate edit-audit +table, or separate request-receipt table. Equivalent existing facilities may be consolidated only if these keys, +atomicity, and reads remain intact. Backend search structures may add physical tables. + +Every key/join carries `scope_id`. IDs use byte-exact comparison, revisions are positive integers, counters are +nonnegative big integers, and timestamps use UTC. `PK` means primary key; `UQ` means unique key. Common timestamps +are omitted. JSON contains bounded metadata/configuration, never a whole-document chunk array. + +| Proposed table / owner | Keys | Minimum fields and purpose | +| --- | --- | --- | +| `pc_rag_runtime` / rag | PK `(scope_id, rag_id)` | `state` (`active/disabled/deleted`), `version`, `effective_config_revision`, `active_generation_id`, `building_generation_id`, `change_seq`, `visibility_epoch`, `deleted_at`; operational state separate from content | +| `pc_rag_documents` / rag | PK `(scope_id, document_id)`; UQ `(scope_id, rag_id, namespace, external_key_hash)` | `rag_id`, full `external_key`, `state` (`active/deleted`), `target_source_type/id`, `target_content_generation`, `target_config_revision`, `last_change_seq`, `version`, `deleted_at`; identity reservation and membership | +| `pc_document_nodes` / document | PK `(scope_id, document_id, revision, node_id)` | `kind` (`section/block`), `parent_node_id`, `ordinal`, `title/text`, `source_locators`, `parser_metadata`; immutable evidence and hierarchy | +| `pc_document_chunks` / document | PK `(scope_id, document_id, revision, chunk_id)`; UQ `(scope_id, document_id, revision, ordinal)` | `section_id`, `text`, `content_digest`, `source_locators`, `origin`, `base_revision`, `edit_source_type/id`, `metadata`; complete effective snapshot | +| `pc_rag_index_generations` / rag | PK `(scope_id, rag_id, generation_id)` | `state` (`building/ready/active/retired/failed`), `config_revision`, immutable `profile_snapshot`, `start_seq`, `applied_seq`, `cutover_seq`, `build_fence`, `error`; independent profile builds | +| `pc_rag_document_publications` / rag | PK `(scope_id, rag_id, generation_id, document_id)` | `document_revision`, `target_content_generation`, `chunk_count`, `index_digest`, `version`; selects entirely indexed content, not membership or head | +| `pc_rag_jobs` / application service | PK `(scope_id, job_id)`; UQ `(scope_id, request_scope_key, operation, idempotency_key)` | `rag_id/document_id` where applicable, `binding_name`, `parent_job_id`, exact Source, `request_digest`, `profile_snapshot`, `target_content_generation`, `generation_id`, `change_seq`, `stage/state`, `attempt`, `lease_token/expires_at`, `next_attempt_at`, `receipt`, sanitized `error`, `actor`; receipts, item work, and index-change work | +| `pc_source_lifecycle` / shared Source service | PK `(scope_id, source_type, source_id)` | `state` (`active/deleted`), `delete_generation`, `deleted_at`, `deleted_by`, `reason`, `delete_operation_id`; initially used for document input and its edit Sources | +| `pc_rag_chunk_index` / rag adapter | PK `entry_id`; UQ `(scope_id, rag_id, generation_id, document_id, revision, chunk_id)` | Complete target key, `searchable_text`, `embedding_input_digest`, `vector_space_id`, `embedding`, `source_digest`; derived exact-chunk entries | + +`request_scope_key` is a server-generated, non-null canonical key: Scope+operation for rag creation, target rag +for its commands, or exact Source for deletion. Internal jobs use deterministic keys; nullable `rag_id` must not +weaken idempotency. The request digest covers operation, target, normalized input descriptor, and preconditions. +An accepted snapshot is pinned: retries return its receipt even if the original path changes. A new file version +requires a new request key. + +Store full external keys alongside fixed-size identity hashes; compare full values on collision and never silently +merge them. Import acceptance reserves the document ID and ownership row; the Artifact is created only after +processing succeeds, so a pending reservation cannot require a document-head foreign key. Content/node/chunk +references resolve to `(scope, family=document, document_id, revision)` and rag references to `family=rag`. +Use composite constraints or transactional validation for same-rag relationships. Public deletion has no SQL cascade. + +Manifests include root SourceRef, parser/OCR/chunker snapshot identifiers, `chunk_count`, `chunks_digest`, and schema +version. Chapter/block parent links stay in the same revision and are acyclic. Chunk locators refer to those blocks; +IDs and order are validated before publication. Edit Source payloads provide audit details without another master table. + +### 3.3. Indexes and backend mapping + +| Access path | Required index / invariant | +| --- | --- | +| List rag documents | `(scope_id, rag_id, state, document_id)` on membership; no full Scope Artifact scan | +| Read revision chunks | Unique ordinal index; keyset cursor fixes revision and last ordinal/chunk ID | +| Resolve Source dependencies | Reverse lineage index; retain root dependencies after every edit | +| Claim work / recover leases | `(binding_name, state, next_attempt_at, job_id)` and `(state, lease_expires_at)` | +| Catch up rebuild | `(scope_id, rag_id, change_seq)` on durable change jobs; retain receipts while builds need them | +| Search published content | Generation/publication keys and chunk-entry UQ; enforce exact revision before ranking | + +SQLite uses FTS5 with stable entry/row-ID mapping and a validated sqlite-vec adapter or another explicitly supported +exact-vector implementation. Missing vector capability must not silently downgrade hybrid requests. SeekDB and +OceanBase use separately verified full-text/vector adapters. `embedding` is a logical column: physical +dimension-specific tables or vector structures may differ, but map to the same exact chunk key. Check index-length +limits without truncating identities. Model/profile changes create generations rather than overwrite old vectors. + +A manual edit transaction writes its system Source, new manifest, complete nodes/chunks snapshot, lineage, target +generation, and index job while preserving membership. An index worker builds invisible entries, validates coverage +and digest, then compare-and-swaps the publication row. A full rebuild captures `change_seq` and applies durable +changes through cutover; inserts, updates, removals, and target changes advance it in their owning transaction. +Source deletion additionally checks the Scope visibility epoch before any per-rag fan-out finishes. + +Cancelled/superseded builds cannot become visible. First-phase retention includes deleted records and indexes; +storage therefore grows with revisions and rebuilds. Expose retained/visible counts and capacity failures. +Restoration, garbage collection, and permanent erasure are deferred, not implicit side effects of DELETE. + ## 4. Targeted asynchronous work and publication An import request fixes the Scope, target `rag`, exact SourceRef, logical document identity, processing configuration @@ -170,11 +253,11 @@ Replaying an idempotency key with a different request digest is a conflict. | Boundary | Atomic records / required checks | | --- | --- | -| Snapshot preparation | Persist bytes before acceptance; failed acceptance may leave an unreferenced snapshot for cleanup | +| Snapshot preparation | Persist bytes before acceptance; failed acceptance may leave an unreferenced snapshot retained for a future GC policy | | Import acceptance | Source acceptance/reuse, validated target request, and durable scheduling intent | | Content commit | Complete manifest/details, provenance, validated membership, content receipt, and index work; manual edits also create their system Source here | | Index publication | Verify complete indexes, exact content target, active configuration, execution ownership, and lifecycle; switch the searchable selection and visibility generation | -| Source revocation | Persist lifecycle tombstone, advance visibility generation, and record cascading cleanup before acknowledging deletion | +| Soft deletion | Persist owning lifecycle marker, advance visibility generation, and save idempotent receipt before acknowledgment; no physical cleanup | Run OCR, embeddings, DDL, and bulk index construction outside these short transactions. Every commit rechecks registration/lease fences, target state, and input/configuration/deletion generations. A newer edit or import @@ -186,6 +269,11 @@ cutover watermark before switching; a partially built generation cannot replace knowledge base cannot switch another's generation. Filesystem/database backup and restore must verify referenced snapshots and index consistency before serving restored retrieval. +Existing `pc_artifact_processing_pending.source_through` requires a positive Source position. Target-only work +uses requested intent generations and durable jobs without inventing a Source position or advancing a Source cursor. +Each claim captures its lease token plus Supervisor/binding fences; checkpoints compare all of them. Expired +ownership permits recovery but never authorizes a late worker to commit. + ## 5. Manual editing, reprocessing, and deletion Initially allow replacement of one existing chunk's text, guarded by the document head ETag. Do not expose chunk @@ -209,18 +297,42 @@ content. Reprocessing manually edited content requires explicit `manual_edits_po Editing while a Source replacement/reparse is pending is rejected; editing committed content still being indexed is allowed and supersedes older index work. Check these conditions atomically with target state. -Deleting an original Source is a Scope-authorized operation that revokes every dependent document revision, -including manually edited revisions and dependencies in other `rag` Artifacts in that Scope. Membership references -do not prevent deletion; `rag` configuration remains. Revocation immediately gates search, caches, original reads, -and ordinary/historical Artifact and chunk reads, while physical cleanup is asynchronous and retryable. Returning -an in-flight result requires a visibility recheck; responses already delivered cannot be recalled. - -Cleanup includes dependent text, OCR/parse caches, indexes, and edit-Source/audit payloads containing that text. -Minimal non-content receipts may remain. An original Source's payload is never rewritten by ordinary editing; -explicit erasure follows its separate lifecycle. Removing one knowledge base does not delete a shared Source. -Deleting an old Source does not revoke revisions derived solely from its replacement, and a revoked old revision -cannot remain as a search fallback. Never delete the user's original file; reclaim managed snapshots only when -no live reference needs them. Late workers must fail the same deletion fence used by revocation. +**The first release implements soft deletion only.** Keep Source payloads, original snapshots, document revisions, +chunks, edit evidence, and indexes physically stored. No restore or permanent-erasure endpoint is provided. +Deletion removes availability through supported application interfaces, not from backups or administrator storage +access. Retained tombstones prevent identity reuse and accidental resurrection. + +| Delete target | Authoritative marker | Immediate effect; retained objects | +| --- | --- | --- | +| Document Source | `pc_source_lifecycle.state=deleted` and Scope visibility epoch | All revisions rooted in it become unavailable, including manual edits across rags in that Scope; rag configuration remains | +| Document | `pc_rag_documents.state=deleted` and rag visibility/change counters | All its revisions/chunks become unavailable via membership, generic reads, and retrieval; Source and other documents remain | +| rag | `pc_rag_runtime.state=deleted` and rag visibility epoch | The knowledge base and its documents become unavailable; Scope, shared Sources, and other rags remain | + +Visibility is a conjunction, not a copied boolean on every row: ordinary content reads require a non-deleted, +enabled rag, active document membership, and non-deleted root Source. Search also requires active generation and +exact published revision. Historical reads can select older revisions but must check their parent/Source markers. +Resolve the root input from the requested revision, not the membership row's newest target Source. Historical +base-revision links are not transitive content dependencies: a fully reparsed replacement declares its own root. +Disabled rag configuration/status remain readable to authorized users; content retrieval is disabled. Re-enabling +a disabled rag does not restore a deleted rag. + +Source deletion needs no synchronous updates to every dependent chunk/membership row: the root marker and epoch +immediately reject reads. Administrative status derives the effective reason. Direct reads of system edit Sources +carrying derived text are gated through their exact document target and immutable root Source reference. Ordinary +Source, generic Artifact, history, chunk, raw-image, and cached reads cannot bypass these checks. +An original Source has its own Scope/lifecycle authority: deleting only a rag or document does not revoke that +Source or its direct original-file read. Edit Sources instead carry derived document text and must check their +document/rag target. Public Source DELETE targets original document inputs; edit Sources are system-managed. + +Keep lineage foreign keys and `RESTRICT` constraints: public DELETE physically deletes no Source/Artifact rows. +Repeated DELETE returns the accepted receipt without advancing counters again. Import into a deleted identity +returns `410`; a new identity must be explicitly chosen. No phase-one operation clears a deletion marker. +In-flight reads recheck visibility before returning; late workers fail commit/publication checks. Already delivered +responses cannot be recalled. + +Deleting an old Source does not revoke revisions derived solely from its replacement. A published old revision +rooted in the deleted Source becomes unavailable immediately, even while its replacement is indexing. Do not use +it as fallback, silently publish an unindexed replacement, or exempt manually edited content from Source checks. ## 6. Retrieval and public interfaces @@ -242,11 +354,168 @@ reads, chunk editing, retrieval, and Source revocation. Do not expose unrestrict that can bypass provenance and ownership validation. Keep HTTP, Python client, and necessary MCP capabilities consistent, with explicit knowledge-base context selection and unchanged Memory retrieval defaults. -Final URLs and schemas belong in `openapi/powercontext.yaml` during implementation, followed by generated clients -and contract checks. This RFC specifies operation semantics rather than presenting unimplemented curl examples. +The following routes and payloads are proposed contracts. Implement them in `openapi/powercontext.yaml`, +generate clients, and run contract checks; they are not already available endpoints. New families and detail tables require versioned migrations on all three backends; existing Sources and Artifact families retain their contracts and are not automatically converted or enrolled in document processing. +### 6.1. API surface + +Let `R = /v1/scopes/{scope_id}/artifacts/rag/{rag_id}` and +`D = /v1/scopes/{scope_id}/artifacts/document/{document_id}`. Routes below are proposed, not released. +Reuse current `ArtifactReference`, `ArtifactAddress`, `SourceTypeReference`, `ETag`, `Location`, pagination, +`ErrorResponse`, and Scope permissions. No parallel generic Artifact CRUD protocol is introduced. + +| Operation | Route / contract | Permission / response | +| --- | --- | --- | +| Create rag | Existing POST `/v1/scopes/{s}/artifacts`, `family=rag`, typed `content`; extend this command with optional `idempotency_key` | `scope.contribute`; `201 ArtifactCreated`, ETag, Location | +| List/read/configure | Existing family list, GET/PUT `R`, revisions/tags; config PUT replaces complete content with current Artifact `If-Match` | Read: `scope.read`; config: `scope.contribute`; `200`, ETag | +| Operational state | New GET/PUT `R/runtime`; PUT accepts `enabled` and `expected_version`, without creating config revisions | Read: `scope.read`; control: `scope.admin`; `200` runtime version/state | +| Import batch | New POST `R/imports`; `idempotency_key`, items with unique `item_key`, namespace/key, and input descriptor | `scope.contribute`; `202` parent job and per-item receipts | +| Browse members | New GET `R/documents`; cursor/state filters, reserved targets, membership version, effective availability, head/published revisions | `scope.read`; `200 items/next_cursor` | +| Document/history | Existing GET `D` and revisions; manifest/provenance with lifecycle checks | `scope.read`; `200`, ETag | +| Chunk/evidence detail | New GET `D/revisions/{rev}/chunks` and `/nodes`; effective chunks versus original evidence; cursor/limit | `scope.read`; `200 items/next_cursor` pinned to revision/view | +| Edit chunk | New PATCH `D/chunks/{chunk_id}`; document `If-Match`, text/reason/idempotency key | `scope.contribute`; `202` new revision and index job | +| Reprocess document | New POST `D/reprocess`; document `If-Match`, idempotency key, explicit `manual_edits_policy=discard` when needed | `scope.contribute`; `202` job | +| Rebuild rag | New POST `R/rebuilds`; `config_revision`, `mode=index_only/reprocess`, idempotency key, edit-discard policy when needed | `scope.admin`; `202` generation/job | +| Inspect/retry work | New GET `/v1/scopes/{s}/rag-jobs/{job_id}`; POST `.../{job_id}/retry` with new idempotency key, same accepted target/input | Read: `scope.read`; retry: `scope.contribute`; `200` status / `202` receipt | +| Query selected rags | New POST `/v1/rag/query`; explicit targets, query, top_k, typed filters and bounded options | `scope.read` for every target; `200` hits and target outcomes | +| Original input | Existing Source GET returns descriptor; new GET `/v1/scopes/{s}/sources/{type}/{id}/content` streams the snapshot | `scope.read`; `200`, media type; no storage credentials | +| Soft-delete document | New DELETE `R/documents/{document_id}`, `expected_version` from membership | `scope.contribute`; `200` receipt | +| Soft-delete rag | New DELETE `R`, `expected_version` from runtime | `scope.admin`; `200` receipt | +| Soft-delete Source | New DELETE `/v1/scopes/{s}/sources/{type}/{id}`; restricted to document Source lifecycle initially | `scope.admin`; `200` receipt | + +DELETE carries `Idempotency-Key` and, where specified, an `expected_version` query parameter. Receipts contain +`operation_id`, target, `state=deleted`, `deleted_at`, and `data_retained=true`, without a cleanup job. Repeated +DELETE returns the original receipt. Administrative jobs can report deleted status without retained text; +normal content GET returns `410` after authorization. There is no `include_deleted` content bypass. + +Creating an empty rag atomically creates initial runtime/generation metadata without scheduling parsing. Config +PUT stores desired settings. Imports use effective settings; config changes do not silently reparse edited content. +Explicit rebuild activates the desired snapshot after verified cutover; `index_only` rejects parser/OCR/chunker +changes. Concurrent imports/edits remain durable and are caught up before switching. Expose desired and effective +revisions separately. Failed rebuilds leave the old effective configuration and indexes. +During ordinary document updates, a valid published revision need not equal the latest head or target generation. +That difference is intentional while indexing; only a successful publication switches it. Lifecycle revocation +always overrides this availability fallback. + +File input uses an authorized Source binding plus relative path, or an exact same-Scope `SourceTypeReference`. +Arbitrary client server paths, URLs, or snapshot locators confer no authority. The plugin captures bytes and validates +media/digest. Reusing a Source still schedules target work. Validate permission and batch shape before acceptance; +per-item capture failures may coexist with successes, but every accepted item atomically persists Source, identity +reservation, job, and intent. Report partial acceptance explicitly. Batch retries return the same item receipts; +failed capture without pinned input needs a new key, while worker retry uses the accepted snapshot. + +### 6.2. Representative payloads + +**Create** uses the existing `family + content` shape. Profiles below are illustrative configured bindings, not +hard-coded defaults. The rag content schema rejects unknown fields and contains no secrets or member arrays. + +```json +{ + "family": "rag", + "idempotency_key": "create-ops-01", + "content": { + "schema_version": "1", + "title": "Operations SOPs", + "summary": "Runbooks and screenshots", + "profiles": { + "parser": "markdown-v1", + "ocr": "rapidocr-local-v1", + "chunker": "heading-paragraph-v1", + "embedding": "docs-embedding-v1", + "retrieval": "hybrid-v1" + } + } +} +``` + +**Import** into an existing rag uses exactly one input alternative per item: + +```json +{ + "idempotency_key": "import-ops-01", + "items": [ + {"item_key": "a", "namespace": "oceanbase-docs", "external_key": "README.md", + "input": {"kind": "file", "binding_name": "local-documents", "path": "README.md"}}, + {"item_key": "b", "namespace": "ops-images", "external_key": "restart.png", + "input": {"kind": "source", "source": {"source_type": "knowledge-document-input", "source_id": "image-42"}}} + ] +} +``` + +The `202` result contains a stable parent job, per-item Source references and reserved document IDs, with +`document=null` until content exists. Parent counts distinguish acceptance from success. Item receipts expose +`stage=accepted/parse/chunk/index/publish`, state, attempt, latest-content/searchable revisions, and error. +Parent aggregation may report `partial_failure` without adding it to individual work-item states. + +**Edit** PATCH `D/chunks/chunk-3` with the document GET's ETag in `If-Match`: + +```json +{"idempotency_key": "edit-03", "text": "Restart the follower before the leader.", "reason": "Correct OCR text"} +``` + +```json +{ + "document": {"family": "document", "artifact_id": "doc-1", "revision": 2}, + "index_job_id": "job-12", + "latest_content_revision": 2, + "searchable_revision": 1, + "chunk": {"chunk_id": "chunk-3", "origin": "manual_edit", "verbatim": false} +} +``` + +**Query** reuses `ArtifactAddress` for each rag. Target revision pins the config head seen by the caller; a stale +head returns conflict. The response separately identifies effective index/configuration, which may lag desired settings. + +```json +{ + "targets": [ + {"scope_id": "project-p", "artifact": {"family": "rag", "artifact_id": "ops", "revision": 1}}, + {"scope_id": "project-q", "artifact": {"family": "rag", "artifact_id": "product", "revision": 3}} + ], + "query": "How should I restart a follower?", + "top_k": 10, + "filters": {"media_types": ["text/markdown", "image/png"]}, + "retrieval": {"mode": "hybrid", "candidate_limit": 100} +} +``` + +Each hit carries Scope, rag/document ArtifactReferences, chunk ID/text/rank/score, SourceTypeReference, supported +locator data, origin/verbatim, and index generation. Return target statuses/errors and `partial`. Authorization +failure rejects the entire request before retrieval; an authorized target's operational failure may yield explicit +partial results. All-target failure remains an error. + +### 6.3. Errors, concurrency, and activation + +| Condition | Contract | +| --- | --- | +| Same key/digest | Replay stable receipt after current authorization/lifecycle checks; deletion replays its tombstone receipt | +| Same key, different digest | `409 idempotency_conflict`, no new work | +| Missing/stale content or config ETag | Existing `428` / `412` precondition responses | +| Stale runtime/membership version, rag config, or pending reparse | `409` with machine-readable reason; no partial commit | +| Deleted target/evidence | `410 resource_deleted` after authorization; no text in error details | +| Unsupported input, invalid profile, oversized edit | `422`; transport byte-limit rejection may use `413` before acceptance | +| Missing backend/model capability | `503`, never an empty match list | +| Accepted asynchronous failure | Job becomes failed/retry_wait; `202` never means processing succeeded | + +Keep the existing error envelope: + +```json +{"error": {"code": "resource_deleted", "message": "The requested document is unavailable.", "details": null}} +``` + +Content writes compare the document head; index writes compare exact target/publication versions. Both update +state and durable work atomically. Replay lookup precedes rechecking an old write precondition but never bypasses +current authorization/deletion. Failed commands roll back their receipts and writes. Staged content is invisible +until complete, and replay responses must not leak text from subsequently deleted targets. + +Migrations create schemas/indexes/capability declarations before activation. New document Sources get lifecycle +rows during acceptance; missing required lifecycle/ownership is an integrity failure, not permission to read. +Existing unrelated families remain unchanged. Reject activation without required backend/profile capability. +Validate upgrade/restart, duplicate requests, read-after-write, publication races, and deletion filters through +public APIs rather than direct table writes. + ## 7. Acceptance and delivery Use Markdown from a pinned `oceanbase/oceanbase` commit and standalone OCR fixtures with checked text/locators. @@ -260,8 +529,8 @@ On SQLite, SeekDB, and OceanBase, verify: and full-text/vector retrieval over document chunks without whole-document JSON scans. - Manual edit provenance, complete snapshots, revision-pinned pagination, updated full-text/vector mappings, reparse conflicts, stale-worker rejection, and generation cutover during concurrent updates. -- Source revocation across shared dependencies, historical/cache/original-read enforcement, retryable cleanup, - and preservation of unrelated documents, replacement-Source revisions, and `rag` configurations. +- Source/document/rag soft deletion, historical/cache/original/edit-Source read enforcement, retained physical rows, + idempotent deletion, and preservation of unrelated documents, replacement-Source revisions, and rag configurations. Use existing issues for delivery: #2441 covers foundations/ingestion, #2442 processing/content/index lifecycle, #2443 retrieval/interfaces, and #2444 operational visibility and cross-backend acceptance. The implementation can @@ -274,7 +543,8 @@ do not infer production capacity from functional fixtures. Complete snapshots amplify storage and write cost even for a one-chunk edit. Separating content and searchable revisions complicates reads and diagnostics. Dedicated consumer restrictions, target work, family writers, and revocation need framework integration beyond a plugin declaration. Three backends add migration and index testing -cost. RapidOCR model packaging and platform compatibility also require explicit maintenance. +cost. RapidOCR model packaging and platform compatibility also require explicit maintenance. Soft deletion retains +all data and indexes, so it is not an erasure feature and requires storage-capacity monitoring. # Rationale and alternatives @@ -303,13 +573,14 @@ and document-specific storage/publication. Topic Memory's family-specific detail The following must be fixed and tested in the implementing changes; they do not defer identity, atomicity, consumer restrictions, or revocation semantics: -- Exact family capability/writer extensions, API schemas, migration names, and backend index layouts. +- Exact Python capability/writer signatures, migration DDL, and backend layouts implementing the contracts above. - Limits for snapshots, decoded image pixels, manifests, chunks, pages, worker concurrency, timeouts, and retries. - Pinned RapidOCR/ONNX/model versions, supported image formats/platforms, and default chunk/embedding profiles. -- Historical revision retention, staging/snapshot garbage collection, and resulting expired-reference responses. +- Future retention/erasure policies and expired-reference responses; phase one retains historical and soft-deleted data. Full edited-document export needs an explicit overlap and edit reconciliation contract. Independent per-`rag` ACLs, -cross-deployment federation, and shared document ownership require separate design work rather than implicit support. +cross-deployment federation, and shared document ownership require separate design work rather than implicit support. Restoration and permanent +erasure also need explicit dependency, authorization, and audit rules before exposure. # Future possibilities diff --git a/docs/zh/rfcs/2570-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md index 602ebc29ec..dd4caeacbb 100644 --- a/docs/zh/rfcs/2570-rag-knowledge-base.md +++ b/docs/zh/rfcs/2570-rag-knowledge-base.md @@ -106,10 +106,10 @@ Markdown 使用 `markdown-it-py` 处理,保留标题、段落、列表、代 | 文档明细 | 每 chunk 一行,以 `(scope, document_id, revision, chunk_id)` 为键,配套章节/block 结构和证据/编辑元数据 | | 成员与目标状态 | rag 归属、逻辑文档键、目标输入/配置,以及生命周期和并发代次 | | 检索投影 | chunk 级全文/向量条目及精确 revision/profile/generation 映射 | -| 处理记录 | 持久目标请求、阶段/结果、重试、租约及可恢复的索引/清理工作 | +| 处理记录 | 持久目标请求、阶段/结果、重试、租约及可恢复的索引工作与删除回执 | 在语义匹配时复用 Artifact、head、lineage、tag 和处理设施。不新增重复的知识库/document/revision 主表,也不将文档数据混入 -Topic Memory 专属 chunk 表。物理表名和各后端辅助索引在实现时确定。 +Topic Memory 专属 chunk 表。下述建议结构确定归属、键和最小字段;后端 DDL 和辅助索引通过迁移落实,不在运行时临时建表。 首期每个 revision 保存**完整 chunk 快照**。100 块的文档保存一条 manifest 和 100 行明细;编辑一个块后再保存一条 manifest 和完整 100 行快照。校验数量、唯一顺序、结构引用,以及覆盖有效文本、顺序和证据映射的摘要。分批暂存数据在完整 revision 提交前不可见。 @@ -119,6 +119,75 @@ Artifact 主体不能保存无界的全文/chunk/向量数组。检索直接 读取返回 manifest;明细分页游标固定 revision、视图和顺序。原始解析证据与编辑后的有效 chunks 分开读取,不能直接拼接重叠 chunks 来导出编辑后的整篇文档。 +### 3.1. 复用的现有表 + +| 现有表/设施 | 用途与必要适配 | +| --- | --- | +| `pc_sources`、`pc_source_journal_heads` | 保持 canonical payload 和 journal 顺序不可变;引用原始快照,不保存派生 chunks | +| `pc_artifacts`、`pc_artifact_heads` | 保存 rag 配置、document manifest 和版本;所有 Artifact 键保留 family;head 不作为检索发布指针 | +| `pc_artifact_lineage_sources`、`pc_artifact_source_locators` | 保留原始输入和编辑 Source;增加/核实 `(scope_id, source_type, source_id)` 反向查询索引 | +| `pc_artifact_lineage_artifacts` 与 tags | 精确 base revision 证据和标签,不代表 rag 成员关系 | +| `pc_artifact_processing_intents`、租约与 binding 状态 | 复用唤醒、执行资格和注册栅栏,逐文档工作单独记录 | +| `pc_scope_settings` | 保留系统管理的 Source 可见代次,和 Source 删除原子递增;不允许用户直接修改 | + +不复用 `pc_artifact_publications` 表示可检索版本,它负责跨 Scope 发布。通用搜索状态按 Scope/family 标识,未经扩展不能支持 +两个 rag 各自的 generation。可复用向量空间定义和适配代码,但 rag 发布选择必须独立;通用 head 的 searchable_text 不是片段索引。 + +### 3.2. 建议关系表结构 + +以下是拟定表名,不表示现有数据库已经包含这些表。基线为七张领域表、一张共享 Source 生命周期表和一张 chunk 索引投影表。 +不重复新增 Source/Artifact/revision 主表,不另建编辑审计表和请求回执表。只有保持下述键、原子性和读取行为时,才能合并到 +语义等价的既有设施中。后端搜索结构可能额外需要物理表。 + +所有键和关联包含 scope_id。ID 按字节精确比较,revision 为正整数,代次为非负大整数,时间使用 UTC。 +PK 表示主键,UQ 表示唯一键;省略公共时间字段。JSON 仅存有界元数据/配置,不保存整篇文档的 chunk 数组。 + +| 建议表/所属能力 | 键 | 最小字段与用途 | +| --- | --- | --- | +| `pc_rag_runtime`/rag | PK `(scope_id, rag_id)` | `state`(active/disabled/deleted)、`version`、`effective_config_revision`、`active_generation_id`、`building_generation_id`、`change_seq`、`visibility_epoch`、`deleted_at`;运行状态与内容分离 | +| `pc_rag_documents`/rag | PK `(scope_id, document_id)`;UQ `(scope_id, rag_id, namespace, external_key_hash)` | `rag_id`、完整 `external_key`、`state`(active/deleted)、`target_source_type/id`、`target_content_generation`、`target_config_revision`、`last_change_seq`、`version`、`deleted_at`;身份预留与成员关系 | +| `pc_document_nodes`/document | PK `(scope_id, document_id, revision, node_id)` | `kind`(section/block)、`parent_node_id`、`ordinal`、`title/text`、`source_locators`、`parser_metadata`;不可变原始解析证据与层次 | +| `pc_document_chunks`/document | PK `(scope_id, document_id, revision, chunk_id)`;UQ `(scope_id, document_id, revision, ordinal)` | `section_id`、`text`、`content_digest`、`source_locators`、`origin`、`base_revision`、`edit_source_type/id`、`metadata`;完整有效内容快照 | +| `pc_rag_index_generations`/rag | PK `(scope_id, rag_id, generation_id)` | `state`(building/ready/active/retired/failed)、`config_revision`、不可变 `profile_snapshot`、`start_seq`、`applied_seq`、`cutover_seq`、`build_fence`、`error`;独立配置构建 | +| `pc_rag_document_publications`/rag | PK `(scope_id, rag_id, generation_id, document_id)` | `document_revision`、`target_content_generation`、`chunk_count`、`index_digest`、`version`;选择索引完整的内容,不代表成员或 head | +| `pc_rag_jobs`/应用服务 | PK `(scope_id, job_id)`;UQ `(scope_id, request_scope_key, operation, idempotency_key)` | 按操作填写 `rag_id/document_id`、`binding_name`、`parent_job_id`、精确 Source、`request_digest`、`profile_snapshot`、`target_content_generation`、`generation_id`、`change_seq`、`stage/state`、`attempt`、`lease_token/expires_at`、`next_attempt_at`、`receipt`、脱敏 `error`、`actor`;回执、逐项任务和索引变更工作 | +| `pc_source_lifecycle`/共享 Source 服务 | PK `(scope_id, source_type, source_id)` | `state`(active/deleted)、`delete_generation`、`deleted_at`、`deleted_by`、`reason`、`delete_operation_id`;首期用于文档输入及其编辑 Source | +| `pc_rag_chunk_index`/rag 后端适配 | PK `entry_id`;UQ `(scope_id, rag_id, generation_id, document_id, revision, chunk_id)` | 完整目标键、`searchable_text`、`embedding_input_digest`、`vector_space_id`、`embedding`、`source_digest`;精确 chunk 的派生索引条目 | + +request_scope_key 是服务端生成的非空规范键:建库使用 Scope+操作,库内命令使用目标 rag,删除 Source 使用精确 Source 身份。 +内部任务使用确定性键,不能因为 rag_id 可空而破坏幂等唯一性。请求摘要覆盖操作、目标、规范化输入描述和前置条件。 +接受后的快照固定,即使原路径内容变化,重试也返回原回执;新文件版本必须使用新请求键。 + +完整 external_key 与定长身份 hash 一起保存;碰撞时比较完整值,不能静默合并。接受导入时预留 document ID 和归属行,内容处理成功后 +才创建 Artifact,因此预留行不能提前要求 document head 外键存在。内容/node/chunk 引用必须定位到 +`(scope, family=document, document_id, revision)`,rag 引用定位到 family=rag。同库关联使用组合约束或事务校验。公开删除不执行 SQL 级联。 + +manifest 包含 root SourceRef、parser/OCR/chunker 快照标识、chunk_count、chunks_digest 和 schema 版本。 +章节/block 父子引用只能位于同一 revision,且不能成环;chunk 定位关联这些 blocks,在发布前校验 ID 和顺序。 +编辑 Source payload 提供审计信息,不新增审计主表。 + +### 3.3. 索引与后端映射 + +| 访问路径 | 必要索引/约束 | +| --- | --- | +| 列出库内文档 | 成员表 `(scope_id, rag_id, state, document_id)`,不扫描 Scope 全部 Artifact | +| 读取 revision chunks | 唯一 ordinal 索引;keyset 游标固定 revision 和最后 ordinal/chunk ID | +| 查 Source 依赖 | lineage 反向索引;每次编辑继续保留 root 依赖 | +| 领取任务/恢复租约 | `(binding_name, state, next_attempt_at, job_id)` 和 `(state, lease_expires_at)` | +| 追平重建 | 持久变更任务 `(scope_id, rag_id, change_seq)`;构建仍需使用的回执不得丢弃 | +| 检索发布内容 | generation/publication 键与 chunk 索引 UQ;排名前约束精确 revision | + +SQLite 使用 FTS5 和稳定的 entry/row-ID 映射,向量使用经过验证的 sqlite-vec 适配或其他明确支持的精确实现。 +缺少向量能力不能静默降级混搜。SeekDB 和 OceanBase 分别验证全文/向量适配。embedding 为逻辑列,实际可能按维度分表或使用 +不同向量结构,但都映射到精确 chunk 键。核实后端索引长度限制,不能截断身份。模型/profile 变化创建新 generation,不覆盖旧向量。 + +人工编辑事务写入系统 Source、新 manifest、完整 nodes/chunks 快照、lineage、目标代次和索引任务,保留成员关系。 +索引 Worker 构建不可见条目、核验覆盖与摘要后,通过 CAS 切换 publication 行。全库重建捕获 change_seq 并追平到切换水位; +新增、更新、移除和目标变化均在所属事务中递增序号。Source 删除另用 Scope 可见代次校验,不等待逐库传播完成。 + +取消/过期构建不能变为可见。首期保留已删除记录和索引,因此存储会随版本和重建增长,需要暴露保留量/可见量及容量不足错误。 +恢复、垃圾回收和永久擦除后续单独设计,不是 DELETE 的隐含副作用。 + ## 4. 定向异步任务与发布 导入请求固定 Scope、目标 rag、精确 SourceRef、逻辑文档身份、处理配置快照和输入/请求代次。接受或复用 Source 与记录目标工作 @@ -140,11 +209,11 @@ failed -> 经授权的显式重试 -> queued | 边界 | 原子记录/必要校验 | | --- | --- | -| 快照准备 | 接受前保存字节;接受失败可能留下待清理的无引用快照 | +| 快照准备 | 接受前保存字节;失败后的无引用快照保留,待后续 GC 策略处理 | | 导入接受 | Source 接受/复用、已验证的目标请求和持久调度意图 | | 内容提交 | 完整 manifest/明细、溯源、已验证的成员关系、内容回执和索引工作;人工编辑在此创建系统 Source | | 索引发布 | 校验完整索引、精确内容目标、生效配置、执行资格和生命周期;切换可检索选择及可见代次 | -| Source 撤销 | 确认删除前持久化生命周期 tombstone、推进可见代次并记录级联清理 | +| 软删除 | 确认前持久化所属生命周期标记、推进可见代次并保存幂等回执;不物理清理 | OCR、embedding、DDL 和批量索引构建都在上述短事务外执行。每次提交重新校验注册/租约栅栏、目标状态及输入/配置/删除代次。 新的编辑或导入使旧发布任务失效。持久工作记录是恢复依据,进程内通知仅加速唤醒。 @@ -153,6 +222,10 @@ OCR、embedding、DDL 和批量索引构建都在上述短事务外执行。每 变更到经验证的水位,不能用部分构建替换当前 generation。重建一个知识库不得切换其他库的 generation。文件系统/数据库备份恢复后, 应验证被引用快照和索引一致性,再开放恢复后的检索。 +现有 `pc_artifact_processing_pending.source_through` 要求正 Source 水位。纯目标任务通过 requested intent 代次和持久任务调度, +不得伪造 Source 水位或推进 Source cursor。领取任务固定自身 lease token 和 Supervisor/binding 栅栏,每次 checkpoint 都比较。 +租约过期允许恢复,不允许旧 Worker 继续提交。 + ## 5. 人工编辑、重处理与删除 首期只允许替换一个已有 chunk 的文字,以 document head ETag 做并发控制;不开放 chunk 增删、合并或重排。超长编辑明确拒绝, @@ -170,14 +243,33 @@ OCR、embedding、DDL 和批量索引构建都在上述短事务外执行。每 `manual_edits_policy=discard`,否则冲突。Source 替换/重解析尚未提交时拒绝编辑;已提交内容仍在索引时允许继续编辑,并使旧索引 任务失效。这些条件必须和目标状态一起原子校验。 -删除原始 Source 是 Scope 授权下的操作,撤销所有依赖 document revision,包括人工编辑版本及同 Scope 其他 rag 中的依赖。 -成员引用不阻止删除,rag 配置保留。撤销立即约束检索、缓存、原文读取及普通/历史 Artifact 和 chunk 读取,物理清理异步执行并可重试。 -在途结果返回前重新校验可见性;已经发送的响应无法收回。 +**首期仅实现软删除。** Source payload、原文快照、document revision、chunks、编辑证据和索引均保留,不提供恢复或永久擦除接口。 +删除表示不能再通过受支持的应用接口获取内容,不代表数据库备份或管理员存储访问中的数据被擦除。保留 tombstone,防止身份复用和意外恢复。 -清理范围包含依赖正文、OCR/解析缓存、索引,以及携带正文的编辑 Source/审计 payload,可保留最小的无正文回执。 -普通编辑不改写原始 Source payload,显式擦除使用独立生命周期。移除一个知识库不删除共享 Source;删除旧 Source 不撤销仅依赖其替代 -Source 的 revision,也不能保留被撤销旧版作为检索兜底。不删除用户原文件,受管理快照仅在没有存活引用时回收。 -迟到 Worker 必须受与撤销相同的删除栅栏约束。 +| 删除对象 | 权威标记 | 立即生效范围与保留对象 | +| --- | --- | --- | +| 文档 Source | `pc_source_lifecycle.state=deleted` 与 Scope 可见代次 | 所有依赖它的 revision 不可用,包括同 Scope 多个 rag 内的人工编辑版本;rag 配置保留 | +| document | `pc_rag_documents.state=deleted` 与 rag 可见/变更计数 | 其全部 revision/chunks 在成员读取、通用读取和检索中不可用;Source 和其他文档保留 | +| rag | `pc_rag_runtime.state=deleted` 与 rag 可见代次 | 知识库及内部文档不可用;Scope、共享 Source 和其他 rag 保留 | + +可见性是多个条件的交集,不需要给每行复制一个删除布尔值:普通内容读取要求 rag 未删除且启用、document 成员有效、根 Source 未删除。 +检索额外检查 active generation 和精确发布 revision。历史读取可指定旧 revision,但仍检查其所属对象和 Source 状态。 +根输入必须取自被读取的 revision,不能使用成员表中最新 target Source。历史 base revision 链接不代表传递性的内容依赖; +完整重解析的替代版本声明自己的根输入。 +停用 rag 的配置/状态仍可供有权限的用户管理,内容检索关闭;重新启用停用 rag 不等于恢复已删除 rag。 + +删除 Source 不必同步更新每个 chunk/成员行,根标记和可见代次即可立即拒绝读取。管理状态根据这些标记计算实际不可用原因。 +携带派生正文的系统编辑 Source 也必须通过精确 document 目标和不可变 root Source 引用校验,普通 Source、通用 Artifact、历史、 +chunk、原图和缓存读取均不能绕过。 +原始 Source 具有独立的 Scope/生命周期授权,单独删除 rag 或 document 不撤销该 Source 及其原文件直读。 +编辑 Source 保存的是派生文字,必须检查 document/rag 目标。公开 Source DELETE 仅针对原始文档输入,编辑 Source 由系统管理。 + +保留 lineage 外键及 RESTRICT 约束,公开 DELETE 不物理删除 Source/Artifact 行。重复删除返回原回执,不再次推进代次。 +向已删除身份导入返回 410;必须显式选择新身份。首期没有清除删除标记的操作。在途读取返回前重新校验,迟到任务不能提交或发布。 +已经发送的响应无法收回。 + +删除旧 Source 不影响仅依赖替代 Source 的 revision。若当前发布的旧 revision 依赖已删 Source,即使替代版本仍在索引,也必须立即不可用。 +不能用旧版兜底、静默发布未完成索引的替代版本,或让人工编辑内容跳过 Source 校验。 ## 6. 检索与公开接口 @@ -193,8 +285,152 @@ Source 的 revision,也不能保留被撤销旧版作为检索兜底。不删 固定 revision 的 chunk 读取、chunk 编辑、检索和 Source 撤销等领域能力。不开放能绕过溯源和归属校验的任意 document 替换。 HTTP、Python client 和必要 MCP 能力保持一致,知识库上下文显式选择,现有 Memory 检索默认行为不变。 -最终 URL 和 schema 在实现时写入 `openapi/powercontext.yaml`,随后生成客户端并运行契约检查。本文确定操作语义,不给出尚未实现的 -curl 示例。新 family 和明细表通过三个后端的版本化迁移引入;既有 Source 和 Artifact family 保持原契约,不自动转换或加入文档处理。 +下述路由和 payload 是建议契约,实现时写入 `openapi/powercontext.yaml`,生成客户端并运行契约检查,不表示接口已经可用。新 family 和明细表通过三个后端的版本化迁移引入;既有 Source 和 Artifact family 保持原契约,不自动转换或加入文档处理。 + +### 6.1. 接口清单 + +约定 `R = /v1/scopes/{scope_id}/artifacts/rag/{rag_id}`, +`D = /v1/scopes/{scope_id}/artifacts/document/{document_id}`。以下路由尚未发布。 +复用现有 ArtifactReference、ArtifactAddress、SourceTypeReference、ETag、Location、分页、ErrorResponse 和 Scope 权限, +不另建通用 Artifact CRUD 协议。 + +| 操作 | 路由/契约 | 权限/返回 | +| --- | --- | --- | +| 创建 rag | 复用 POST `/v1/scopes/{s}/artifacts`,family=rag 与类型化 content;为此命令扩展可选 idempotency_key | scope.contribute;201 ArtifactCreated、ETag、Location | +| 列出/读取/配置 | 复用 family list、GET/PUT `R`、revisions/tags;配置 PUT 携带当前 Artifact If-Match,完整替换 content | 读 scope.read,配置 scope.contribute;200、ETag | +| 运行状态 | 新增 GET/PUT `R/runtime`;PUT 接受 enabled 和 expected_version,不生成配置 revision | 读 scope.read,控制 scope.admin;200 运行版本/状态 | +| 批量导入 | 新增 POST `R/imports`;idempotency_key、items,每项有唯一 item_key、namespace/key 和输入描述 | scope.contribute;202 父任务和逐项回执 | +| 浏览成员 | 新增 GET `R/documents`;cursor/state 过滤,包含预留目标、成员版本、实际可用状态及内容/发布版本 | scope.read;200 items/next_cursor | +| 文档/历史 | 复用 GET `D` 和 revisions;manifest/溯源均检查生命周期 | scope.read;200、ETag | +| Chunk/证据明细 | 新增 GET `D/revisions/{rev}/chunks` 和 `/nodes`;分别返回有效 chunks、原始证据,支持 cursor/limit | scope.read;200 items/next_cursor,固定 revision/view | +| 编辑 chunk | 新增 PATCH `D/chunks/{chunk_id}`;document If-Match、text/reason/idempotency_key | scope.contribute;202 新 revision 和索引任务 | +| 重处理 document | 新增 POST `D/reprocess`;document If-Match、幂等键,必要时显式 manual_edits_policy=discard | scope.contribute;202 任务 | +| 重建 rag | 新增 POST `R/rebuilds`;config_revision、mode=index_only/reprocess、幂等键和必要的编辑丢弃策略 | scope.admin;202 generation/任务 | +| 查看/重试任务 | 新增 GET `/v1/scopes/{s}/rag-jobs/{job_id}`,POST `.../{job_id}/retry` 使用新幂等键,保留原接受目标/输入 | 读 scope.read,重试 scope.contribute;200 状态/202 回执 | +| 多库检索 | 新增 POST `/v1/rag/query`;显式 targets、query、top_k、类型化 filters 和有界选项 | 每个目标 scope.read;200 命中和逐目标结果 | +| 原始输入 | 现有 Source GET 返回描述;新增 GET `/v1/scopes/{s}/sources/{type}/{id}/content` 返回快照流 | scope.read;200、媒体类型,不暴露存储凭据 | +| 软删除 document | 新增 DELETE `R/documents/{document_id}`,expected_version 取成员版本 | scope.contribute;200 回执 | +| 软删除 rag | 新增 DELETE `R`,expected_version 取运行状态版本 | scope.admin;200 回执 | +| 软删除 Source | 新增 DELETE `/v1/scopes/{s}/sources/{type}/{id}`,首期仅适用文档 Source 生命周期 | scope.admin;200 回执 | + +DELETE 携带 Idempotency-Key,要求 expected_version 的操作将其作为查询参数。回执包含 operation_id、目标、state=deleted、 +deleted_at 和 data_retained=true,不隐含清理任务。重复 DELETE 返回原回执。管理任务可报告删除状态,但不返回保留的正文; +普通内容 GET 在授权后返回 410,不提供 include_deleted 内容绕过选项。 + +创建空 rag 时原子创建初始运行/generation 元数据,不调度解析。配置 PUT 保存目标配置,导入使用生效配置,配置变化不静默重解析人工编辑。 +显式 rebuild 在校验切换后激活目标快照,index_only 拒绝 parser/OCR/chunker 变化。重建期间的导入/编辑持久保存,切换前追平。 +分别展示目标和生效 revision;重建失败保留旧生效配置与索引。 +普通文档更新期间,有效发布 revision 无须等于最新 head 或目标代次,这是索引期间的预期差异;成功发布后才切换。 +生命周期撤销始终优先于旧版可用的兜底规则。 + +文件输入使用已授权 Source binding 加相对路径,或同 Scope 精确 SourceTypeReference。客户端任意填写的服务器路径、URL 或快照位置 +不构成访问授权。插件负责捕获字节和校验媒体/摘要,复用 Source 也须调度目标工作。接受前校验权限和批次形状;逐项采集失败可以与 +成功项共存,但每个接受项必须原子保存 Source、身份预留、任务和 intent,明确报告部分接受。批次重试返回原逐项回执; +没有固定输入的采集失败使用新键重新提交,Worker 重试则继续使用已接受快照。 + +### 6.2. 典型请求与响应 + +**创建**沿用 family + content。以下 profile 是示例部署 binding,不是硬编码默认值。rag content schema 拒绝未知字段,不保存密钥或成员数组。 + +```json +{ + "family": "rag", + "idempotency_key": "create-ops-01", + "content": { + "schema_version": "1", + "title": "Operations SOPs", + "summary": "Runbooks and screenshots", + "profiles": { + "parser": "markdown-v1", + "ocr": "rapidocr-local-v1", + "chunker": "heading-paragraph-v1", + "embedding": "docs-embedding-v1", + "retrieval": "hybrid-v1" + } + } +} +``` + +**导入**已有 rag,每项只选择一种输入形式: + +```json +{ + "idempotency_key": "import-ops-01", + "items": [ + {"item_key": "a", "namespace": "oceanbase-docs", "external_key": "README.md", + "input": {"kind": "file", "binding_name": "local-documents", "path": "README.md"}}, + {"item_key": "b", "namespace": "ops-images", "external_key": "restart.png", + "input": {"kind": "source", "source": {"source_type": "knowledge-document-input", "source_id": "image-42"}}} + ] +} +``` + +202 响应包含稳定父任务、逐项 Source 引用和预留 document ID;内容尚未生成时 document=null。父任务计数区分接受和成功。 +逐项回执暴露 stage=accepted/parse/chunk/index/publish、state、attempt、最新内容/可检索 revision 和 error。 +父任务聚合可报告 partial_failure,不把它加入单项工作状态机。 + +**编辑**使用 PATCH `D/chunks/chunk-3`,If-Match 为 document GET 返回的 ETag: + +```json +{"idempotency_key": "edit-03", "text": "Restart the follower before the leader.", "reason": "Correct OCR text"} +``` + +```json +{ + "document": {"family": "document", "artifact_id": "doc-1", "revision": 2}, + "index_job_id": "job-12", + "latest_content_revision": 2, + "searchable_revision": 1, + "chunk": {"chunk_id": "chunk-3", "origin": "manual_edit", "verbatim": false} +} +``` + +**检索**的每个 rag 复用 ArtifactAddress。目标 revision 固定调用者所见的配置 head,过期时返回冲突。 +响应单独标明生效索引/配置,它可能落后于目标配置。 + +```json +{ + "targets": [ + {"scope_id": "project-p", "artifact": {"family": "rag", "artifact_id": "ops", "revision": 1}}, + {"scope_id": "project-q", "artifact": {"family": "rag", "artifact_id": "product", "revision": 3}} + ], + "query": "How should I restart a follower?", + "top_k": 10, + "filters": {"media_types": ["text/markdown", "image/png"]}, + "retrieval": {"mode": "hybrid", "candidate_limit": 100} +} +``` + +每条命中包含 Scope、rag/document ArtifactReference、chunk ID/text/rank/score、SourceTypeReference、支持的定位、 +origin/verbatim 和索引 generation。响应返回逐目标状态/错误及 partial。权限失败在检索前拒绝整个请求;已授权目标的运行失败 +可返回明确部分结果,全部目标失败仍是错误。 + +### 6.3. 错误、并发与能力启用 + +| 情况 | 契约 | +| --- | --- | +| 相同键/摘要 | 校验当前授权/生命周期后重放稳定回执;删除重放其 tombstone 回执 | +| 同键不同摘要 | 409 idempotency_conflict,不创建新工作 | +| 缺失/过期内容或配置 ETag | 复用 428/412 前置条件响应 | +| 过期运行/成员版本、rag 配置或正在重解析 | 409 和机器可读原因,不部分提交 | +| 目标/证据已删除 | 授权后 410 resource_deleted,错误不包含正文 | +| 不支持输入、非法配置、过长编辑 | 422;接受前传输字节限制可返回 413 | +| 缺少后端/模型能力 | 503,不当作无命中 | +| 已接受任务异步失败 | 任务 failed/retry_wait;202 不表示处理完成 | + +沿用现有错误封装: + +```json +{"error": {"code": "resource_deleted", "message": "The requested document is unavailable.", "details": null}} +``` + +内容写入比较 document head,索引写入比较精确目标/publication 版本,都原子更新状态和持久工作。 +重放查询先于旧写入前置条件的再次检查,但不能绕过当前权限/删除。失败命令回滚回执和业务写入,暂存内容完整前不可见, +重放响应也不能泄露随后被删除目标的文字。 + +迁移先创建 schema/索引/能力声明,再启用功能。新文档 Source 在接受时创建生命周期行,缺少必要生命周期/归属是完整性错误, +不能默认允许读取。无关 family 不变;缺少要求的后端/profile 能力时拒绝启用。通过公开 API 验证升级/重启、重复请求、 +写后读、发布竞态和删除过滤,不只直接写表验证。 ## 7. 验收与交付 @@ -204,7 +440,7 @@ curl 示例。新 family 和明细表通过三个后端的版本化迁移引入 - 已有 Source 复用、幂等重试、无 document 的首次失败、进程重启、内容/成员/工作原子提交,以及索引失败时旧版本可检索。 - 真实 RapidOCR、非法/不支持输入和无文字结果、Markdown 图片引用保留,以及不扫描整篇 JSON 的 chunk 全文/向量检索。 - 人工编辑溯源、完整快照、固定 revision 分页、全文/向量映射更新、重解析冲突、迟到 Worker 拒绝,以及并发更新下的 generation 切换。 -- 共享依赖上的 Source 撤销,历史/缓存/原文读取校验,可重试清理,以及无关文档、替代 Source 版本和 rag 配置的保留。 +- Source/document/rag 软删除,历史/缓存/原文/编辑 Source 读取校验、物理数据保留、幂等删除,以及无关文档、替代 Source 版本和 rag 配置的保留。 沿用现有 Issue:#2441 负责基础与导入,#2442 负责处理/内容/索引生命周期,#2443 负责检索和接口,#2444 负责运行可见性与三后端验收。 实现可采用一个集成分支和 PR,按这四个阶段评审。本 RFC PR 不完成这些实施 Issue。随实现发布支持格式、模型版本、资源限制和恢复说明, @@ -213,7 +449,7 @@ curl 示例。新 family 和明细表通过三个后端的版本化迁移引入 # 缺点 完整快照使单块编辑也增加存储和写入成本。区分内容版本与检索版本增加读取和诊断复杂度。专用消费限制、定向任务、family writer 和 -撤销机制需要超出插件声明的框架适配。三后端增加迁移和索引测试成本,RapidOCR 模型分发及平台兼容性也需要明确维护。 +撤销机制需要超出插件声明的框架适配。三后端增加迁移和索引测试成本,RapidOCR 模型分发及平台兼容性也需要明确维护。软删除保留全部数据和索引,不是擦除能力,需要监控存储容量。 # 设计理由与替代方案 @@ -238,12 +474,12 @@ curl 示例。新 family 和明细表通过三个后端的版本化迁移引入 以下内容须在对应实现中固定并测试,不延后身份、原子性、消费限制和撤销语义: -- 精确的 family 能力/writer 扩展、API schema、迁移名称和后端索引布局。 +- 实现上述契约的 Python 能力/writer 签名、迁移 DDL 和后端索引布局。 - 快照、解码图片像素、manifest、chunk、分页、Worker 并发、超时和重试限制。 - 固定的 RapidOCR/ONNX/模型版本、支持的图片格式/平台,以及默认切块/embedding profiles。 -- 历史 revision 保留期、暂存/快照垃圾回收及过期引用响应。 +- 后续保留/擦除策略及过期引用响应;首期保留历史和软删除数据。 -完整编辑文档导出需要明确重叠和编辑合并契约。独立 rag ACL、跨部署联合查询和共享 document 归属需要单独设计,不隐式提供。 +完整编辑文档导出需要明确重叠和编辑合并契约。独立 rag ACL、跨部署联合查询和共享 document 归属需要单独设计,不隐式提供。恢复和永久擦除还需明确依赖、授权与审计规则后才能开放。 # 后续可能性 From f498b0d948ab3a7c48c8cb090ab11858ef8b2dea Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Tue, 10 Nov 2026 17:37:54 +0800 Subject: [PATCH 04/13] docs(rfc): simplify rag ingestion and reuse shared APIs --- docs/en/rfcs/2570-rag-knowledge-base.md | 864 ++++++++++-------------- docs/zh/rfcs/2570-rag-knowledge-base.md | 622 +++++++---------- 2 files changed, 615 insertions(+), 871 deletions(-) diff --git a/docs/en/rfcs/2570-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md index 6cc53c85ed..4fb746b473 100644 --- a/docs/en/rfcs/2570-rag-knowledge-base.md +++ b/docs/en/rfcs/2570-rag-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570: Document knowledge bases with rag Artifacts" -description: "A proposal for plugin-based knowledge bases with immutable document Sources, versioned chunks, hybrid retrieval, and recoverable processing." +description: "A proposal for OpenDAL document ingestion, simple Markdown chunking, plugin-owned retrieval, and versioned knowledge bases using existing Source and Artifact facilities." --- - Proposal Name: `rag_knowledge_base` @@ -11,580 +11,430 @@ description: "A proposal for plugin-based knowledge bases with immutable documen # Summary -Add document knowledge bases through one document Source plugin and two Artifact families: `document` and `rag`. -A Scope can contain multiple user-created `rag` Artifacts. Users import files into a selected `rag`; background work -parses immutable input, produces a whole-document Artifact with separately stored chunks, associates it with that -knowledge base, and publishes full-text/vector indexes. This proposal defines design intent, not released APIs. +Provide knowledge bases through a document Source plugin and the `document` and `rag` Artifact families. A Scope +contains multiple user-created rags; each document Source and document belongs to exactly one rag. OpenDAL captures +local files, Markdown and image OCR share a simple Markdown chunker, and existing Artifact Workers prepare content +and indexes before committing a document revision together. Reuse existing core metadata schemas, CRUD, supervision, +and generic index storage; add only document-specific detail and target records. This is a proposed contract, not +released functionality. # Motivation -Business descriptions and task SOPs need passage retrieval with exact evidence, explicit updates, and deletion. -Extracted memories complement this use case but do not preserve all document content. A knowledge base must keep -original input, processed content, and searchable versions distinct so that failed processing cannot corrupt an -existing result and manual corrections do not masquerade as original evidence. +Business descriptions and SOPs need passage retrieval over complete documents, exact provenance, explicit updates, +and predictable deletion. Memory extraction does not preserve every passage. The first implementation should cover +that workflow without a second task platform, a per-rag index-generation system, or duplicate Artifact master tables. -Reuse PowerContext's Source definitions, Artifact management, plugin registration, Scope authorization, processing -supervision, and persistence. Add the document-specific contracts they do not yet provide instead of introducing -a parallel knowledge-base object system or a general workflow engine. +Source snapshots and historical document revisions remain evidence. Knowledge-base retrieval is a derived projection, +maintained independently of existing Memory retrieval data and defaults. Reuse infrastructure without treating the +current plugin declaration as already sufficient for targeted ingestion, separate chunk storage, or deletion checks. # Guide-level explanation -A Scope remains a project or workspace and the initial authorization boundary. A knowledge base is a `rag` Artifact -within that Scope, with its own name and processing/retrieval configuration. Renaming or deleting it does not rename -or delete the Scope. Knowledge bases in the same Scope are not separate confidentiality boundaries. +1. Create a `rag` through standard Artifact creation in an existing Scope. +2. Select the rag and a local directory/file. The client uses a configured local OpenDAL Source plugin; users do not + supply Source IDs, namespaces, hashes, or document IDs. +3. Inspect the latest per-file processing status. Accepted input is not yet searchable content. +4. Search documents owned by the selected rag, or explicitly select multiple authorized rags. +5. Change a file and import again. Identical successfully processed input is skipped; changed content creates a new + Source and revision of the same logical document. +6. Edit or remove a chunk. Both create a new document revision; old revisions and their chunk content remain intact. + +Scope remains the authorization boundary. Source/document ownership is exclusive to a rag, not cross-rag sharing. +Importing the same file into two rags creates different Sources/documents even if their physical snapshots are deduplicated. +The initial release supports Markdown and independently imported text images using RapidOCR with ONNX Runtime. +Markdown image references are retained without fetching or OCR-processing them. SQLite, SeekDB, and OceanBase must +support the workflow, with one selected persistence backend per deployment. + +PDF, Office, plain TXT ingestion, semantic/LLM chunking, complex layout/table reconstruction, scheduled directory +synchronization, per-rag embedding spaces, independent online rag index cutovers, a full management UI, and a +large-corpus performance gate are out of scope. The UI can later use the per-file status contract. -For example, a team creates `Product docs` and `Operations SOPs` in one Scope: +# Reference-level explanation + +## 1. Ownership and plugin configuration + +```text +Scope + +-- rag K1 -- owns --> original Sources -- derive --> document revisions -- chunks + +-- rag K2 -- owns --> different Sources/documents, even for the same local file + +Source plugin: OpenDAL capture and immutable snapshot access +Document plugin: Markdown / OCR -> Markdown -> chunks, revisions and provenance +rag plugin: collection management, retrieval policy and index adaptation +Shared facilities: Source/Artifact APIs, Supervisor/Worker, transactions, database/search adapters +``` -1. Create both empty `rag` Artifacts through Artifact management; no document input is required. -2. Import Markdown into `Product docs` and a standalone text image into `Operations SOPs`. -3. Receive durable import receipts and inspect parsing, indexing, and failure status. -4. Search either knowledge base, or explicitly select both. Documents appear automatically after processing and - become searchable after index publication; users do not manually attach generated documents. -5. Replace an original file or edit an existing chunk. A new document revision becomes searchable only after its - indexes are ready. A failed update leaves the previous published revision available unless revoked or removed. +A rag is configuration and collection identity, not a Source-generated output. It can be empty. Its name/configuration +uses Artifact revisions; deletion uses existing head governance. There is no separate rag runtime table or runtime +status API. Parsing progress belongs to the imported file, not to rag configuration revisions. -The initial release supports Markdown and independently imported images using RapidOCR with ONNX Runtime. -Markdown image references are preserved without fetching or OCR-processing their targets. SQLite, SeekDB, and -OceanBase must each support the complete functional workflow; one deployment uses one selected backend. +`document` represents a whole document. Its stable identity is scoped by `(scope, rag, collection, relative_path)`; +chunks are internal revision details. The server derives `collection` from the registered storage binding/instance +and normalized root, not a fresh scan ID. Source payloads contain immutable owner rag identity, original path, +relative path, media type, content digest, and a managed snapshot reference. Tasks snapshot processing configuration; +mutable task status and parsed text never enter Source payloads. Only the document pipeline directly consumes this +Source type, enforced at selection, execution, and commit. -Plain TXT, PDF, Office, automatic synchronization, production reranking, agentic retrieval, a complete management -UI, and a tens-of-thousands-of-documents benchmark are not initial acceptance requirements. Task status and recovery -APIs must nevertheless support a future UI. Applications remain responsible for answering questions from results. +The three logical plugins may ship in one package. The knowledge-base package owns its embedding/index configuration, +separately from Memory or other main-path configuration. Explicit plugin settings win; otherwise installation may +initialize compatible values from the main path and persist a resolved configuration snapshot. Keep credential +references rather than copying secrets into Artifact content. Later main-path changes do not silently change the +plugin profile. Missing/incompatible settings fail activation. Parser/chunker settings may vary by rag; the initial +embedding/index profile is plugin-level, shared by its document family within each Scope. -# Reference-level explanation +Reuse model invocation and SQL adapters, but isolate by family, index definition, and vector-space/profile identity. +No queries implicitly mix Memory rows with document rows. A plugin model/dimension change uses the existing family +rebuild mechanism, with its availability limitations, not a new per-rag publication protocol. -## 1. Identity, ownership, and provenance +## 2. OpenDAL ingestion and duplicate detection + +Use the existing OpenDAL/`opendalfs` integration for local listing and reads. The plugin instance must run where the +selected local path exists; a remote Server cannot interpret an arbitrary client-local path. Resolve relative paths +against the configured root, reject escapes, and keep a stable normalization/symlink policy. Original Markdown bytes +and images are captured into managed immutable snapshots before Source acceptance. Hash the exact bytes saved; +never hash one read and process a later read of a changing file. Read errors or detected unstable capture are retryable. ```text -Scope - +-- rag K1 -- membership --> document D1 -- revisions --> chunks - +-- rag K2 -- membership --> document D2 -- revisions --> chunks - ^ -immutable document Source -------+ content provenance +file_key = (scope_id, rag_id, collection_id, normalized_relative_path) +content_digest = SHA256(captured raw bytes) +source_key = hash(source schema version, file_key, content_digest) +processing_key = hash(content_digest, parser/OCR/model versions and settings, + Markdown normalizer version, chunker version and settings) +index_key = hash(complete embedding inputs, plugin profile and projection versions) ``` -| Object | Identity and responsibility | -| --- | --- | -| `rag` Artifact | User-created configuration and collection identity; members and processing progress do not create configuration revisions | -| Document Source | Immutable original input descriptor: original path, managed snapshot reference, digest, media type, and captured metadata | -| `document` Artifact | One whole logical document, with a stable ID and increasing content revisions; initially belongs to exactly one `rag` | -| Chunk | Internal content and retrieval unit of a document revision, not a Source or independent Artifact | -| Index generation | A `rag`-scoped index configuration/build, separate from content revisions and plugin registration generations | - -Logical document identity is `(scope, rag, source_namespace, external_key)`. Reimporting that identity updates the -same document; importing the same path into another `rag` creates a separate document. Content digests do not merge -logical identities. An immutable Source may be explicitly reused by multiple knowledge bases in the same Scope; -this does not create cross-Scope Source identity or shared document ownership. - -Source lineage, `rag` membership, and the searchable revision selection are separate relationships. Tags cannot -substitute for ownership. Original paths aid provenance; reads use the captured immutable snapshot rather than -whatever currently exists at that path. Raw Markdown bytes and original images live in an OpenDAL-managed local -directory, using the existing OpenDAL/`opendalfs` integration where suitable. - -Define a dedicated document Source type, provisionally `knowledge-document-input`. Only the document pipeline may -directly consume it. Enforce this at input selection, execution, and commit validation, not just through a naming -convention. Do not automatically expose it through generic evidence feeds consumed by other Artifact families. -Parsing output, OCR text, chunks, index pointers, and progress never mutate the Source payload. - -## 2. Plugin responsibilities and framework integration - -| Logical plugin | Owned behavior | -| --- | --- | -| Document Source | File validation, immutable snapshots, Source acceptance, and authorized original-content reads | -| `document` Artifact | Parsing, OCR, chunking, content revisions, chunk reads, manual edits, and evidence mappings | -| `rag` Artifact | Configuration, membership, index generations, publication, hybrid retrieval, and selected multi-base queries | - -These are three logical plugins, not three required processes or distributions. Parser/OCR/chunker implementations -are replaceable components within `document`; index and retrieval adapters belong to `rag`, using shared database -and model facilities. Defaults may be referenced by `rag`, while component schemas are validated by their owner. - -Reuse Source and Artifact plugin registration and existing management/read conventions. The current generation -model must be extended for explicit `rag` creation, domain detail storage, and target-specific work: an empty `rag` -is a managed object, not the output of Source consumption. Do not create a fake input Source to schedule its creation -or claim the generic plugin manifest alone supplies these capabilities. Existing system-generated management -provenance may still be recorded without triggering document processing. - -A knowledge-base application service coordinates the use case through registered family capabilities. It is not -a fourth domain plugin. Each writer owns its records and participates in the caller's shared database transaction; -plugins do not write each other's private tables or commit independently. This uses one deployment database, not -a distributed transaction between plugin services. The document parser cannot choose the target `rag`. - -## 3. Parsing and chunk storage - -Markdown processing uses `markdown-it-py`, retaining headings, paragraphs, lists, code, tables, and links. -Map parser locations back to original UTF-8 bytes; do not fabricate inline precision from block-level line ranges. -RapidOCR with ONNX Runtime processes standalone images with pinned model identities, image-size limits, and -coordinate mapping back to the original image after preprocessing. Preserve actual OCR text, confidence, and -regions. Distinguish unsupported input, invalid encoding, damaged images, no recognized text, missing models, -and timeouts. Do not use generation models to fill in or rewrite OCR output. - -Both paths produce validated blocks, sections, and source locators for a configurable heading/paragraph/length -chunker. Preserve ordering, overlap/continuation, neighboring chunks, and potentially multiple source spans or -image regions. A locator describes actual evidence; OCR confidence is an engine score, not a promised accuracy. - -| Storage | Proposed representation | +mtime/size may help select work but are not proof of identical content. Compare full identity fields on hash collision; +never truncate paths or merge them by digest alone. User-visible Source IDs are generated by the Source framework +using the plugin's deterministic identity rules. Reusing an existing immutable Source preserves its first canonical +capture metadata rather than rewriting mtime or annotations. + +| Observation | Required behavior | | --- | --- | -| Existing Artifact records and heads | One bounded manifest per document revision: title/summary, original Source reference, configuration identifiers, schema version, chunk count, and collection digest | -| Document detail records | One row per chunk keyed by `(scope, document_id, revision, chunk_id)`, plus section/block structure and evidence/edit metadata | -| Membership and target state | `rag` ownership, logical document key, desired input/configuration, and lifecycle/concurrency generations | -| Retrieval projections | Chunk-level full-text/vector entries and exact revision/profile/generation mappings | -| Processing records | Durable target requests, stage/results, retries, leases, and recoverable indexing work and deletion receipts | - -Reuse Artifact, head, lineage, tag, and processing facilities where their semantics match. Do not add duplicate -knowledge-base/document/revision master tables or mix document rows into family-specific Topic Memory chunk tables. -The proposed schema below fixes ownership, keys, and minimum fields. Backend-specific DDL and auxiliary indexes -are finalized through migrations, not runtime table creation. - -Each revision initially stores a **complete chunk snapshot**. A 100-chunk document has one manifest and 100 detail -rows; editing one chunk creates another manifest and a complete 100-row snapshot. Validate counts, unique ordering, -structure references, and a digest covering effective text, order, and evidence mappings. Batched staging remains -invisible until the complete revision is committed. This deliberately accepts storage amplification for simpler -revision reads and recovery; shared chunk bodies across revisions are deferred. - -The main Artifact content must not contain an unbounded full-text/chunk/vector array. Search accesses chunk indexes -directly, then batch-loads exact hits and same-revision neighbors. Generic Artifact reads return the manifest; -detail pagination fixes revision, view, and ordering in the cursor. Distinguish original parsed evidence from -effective edited chunks. Overlapping chunks cannot simply be concatenated into an edited full-document export. - -### 3.1. Existing tables to reuse - -| Existing table / facility | Use and required adaptation | +| Same file/content/processing key, successful result | Reuse Source and document; no new revision; check index readiness separately | +| Same target already pending/running | Coalesce; do not launch another parse | +| Same input, previous processing failed | Retain pinned Source and allow bounded retry; a capture checkpoint is not processing success | +| Same path, changed bytes | Accept new Source; process a new revision of the same document | +| Same bytes, changed parser/OCR/chunker | Reuse Source; explicitly reprocess to a new revision | +| Only embedding/index profile changed | Reindex committed chunks without rerunning OCR | +| Different path or different rag, identical bytes | Different logical document and Source; optional physical snapshot reuse only | +| Deleted identity encountered | Reject implicit resurrection; no restore in phase one; require an explicitly new identity | + +Returning to previously seen bytes still compares against the current target/result: finding an old Source is not +proof the current document already represents it. Renames are new paths initially; missing files do not imply deletion. +Manual edits/removals must not be overwritten by an unchanged-file scan. Changed input or explicit reprocessing of +an edited document requires `manual_edits_policy=discard`; without it, retain the old committed revision and report +an actionable conflict. The input Source can already be captured while content processing remains blocked. + +Use Source `collect` capability discovery and existing add/status/control operations. A plugin-specific `scan_token` +in the capability input identifies one explicit scan target, generated by the client. A retried add with the same +input reuses that target; a new explicit import uses a new token but the same collection/file identities. The plugin +scans once per token and remains available for future targets; it does not periodically rescan. Existing Source +status describes collection, not full document processing or a batch history. New scans must consult document +processing state as well as capture checkpoints, so unchanged capture cannot hide downstream failures. + +## 3. Markdown normalization and simple chunking + +Both inputs produce a common Markdown view: + +```text +Markdown bytes -> markdown-it-py structure / original-byte mapping --+ + +-> rule-based chunks +Image -> RapidOCR -> text lines/regions -> normalized Markdown -----+ +``` + +For OCR, preserve actual text, order, confidence and original-image regions, accounting for preprocessing transforms. +Markdown conversion escapes syntax and groups lines/paragraphs; it does not invent headings, repair text with an LLM, +or reconstruct complex tables. Keep normalized-text spans mapped to OCR lines and image regions. Normalized Markdown +is derived processing content, never a replacement for the image Source. A locator must state its actual precision. + +Use headings, paragraphs, lists, and code blocks; merge short blocks up to `max_chunk_chars`, split oversized blocks +at sentence/length boundaries, and optionally retain `overlap_chars` at split boundaries. Validate overlap is smaller +than the maximum. Preserve heading paths, order and continuation flags; do not require a standalone section-tree +subsystem. Before embedding, enforce the actual model token budget, including any heading/prefix context; do not +silently truncate. Chunker changes that alter boundaries are versioned configuration changes. + +Source media validation, UTF-8 errors, bad/unsupported images, no recognized text, missing OCR models, excessive +pixels, and timeouts have explicit outcomes. Pin/test real RapidOCR and ONNX/model versions. Normalized Markdown may +be computed transiently; an independent parsed-document cache is not required. Chunks store effective text and +bounded source mappings, not vectors. The Artifact manifest remains bounded and does not embed all chunks. + +## 4. Persistence: unchanged core schemas and three supporting tables + +Existing core metadata table definitions are unchanged by this proposal. New family records, declarations, and +indexes use their established schemas. This is a constraint on migrations, not a claim that code changes are unnecessary. + +| Reuse | Purpose and required code integration | | --- | --- | -| `pc_sources`, `pc_source_journal_heads` | Keep canonical payloads and journal order immutable; reference original snapshots, not derived chunks | -| `pc_artifacts`, `pc_artifact_heads` | Store rag configuration and document manifests/revisions; keep family in every Artifact key; head is not a retrieval-publication pointer | -| `pc_artifact_lineage_sources`, `pc_artifact_source_locators` | Preserve root input and edit Sources; add/verify reverse lookup on `(scope_id, source_type, source_id)` | -| `pc_artifact_lineage_artifacts` and tags | Exact base-revision evidence and tagging, not rag membership | -| `pc_artifact_processing_intents`, leases, binding states | Reuse wakeup, ownership, and registration fences; store per-document work separately | -| `pc_scope_settings` | Reserve a system-owned Source-visibility epoch, advanced atomically on Source deletion; not user-editable | - -Do not reuse `pc_artifact_publications` for searchable revisions: it represents cross-Scope publication. Generic -search state is keyed by Scope/family and cannot select independent generations for two rags without extension. -Reuse vector-space definitions and adapter code where applicable, but keep rag publication explicit. The generic -head's `searchable_text` is not the passage index. - -### 3.2. Proposed relational schema - -These are proposed names, not installed schema. The baseline has seven domain tables, one shared Source lifecycle -table, and one chunk-index projection. It adds no duplicate Source/Artifact/revision master, separate edit-audit -table, or separate request-receipt table. Equivalent existing facilities may be consolidated only if these keys, -atomicity, and reads remain intact. Backend search structures may add physical tables. - -Every key/join carries `scope_id`. IDs use byte-exact comparison, revisions are positive integers, counters are -nonnegative big integers, and timestamps use UTC. `PK` means primary key; `UQ` means unique key. Common timestamps -are omitted. JSON contains bounded metadata/configuration, never a whole-document chunk array. - -| Proposed table / owner | Keys | Minimum fields and purpose | +| `pc_sources`, Source journal, connector checkpoints | Immutable inputs, capture identity and acquisition progress | +| `pc_artifacts`, `pc_artifact_heads` | rag configuration, document revision manifest, active/retired state and governance CAS | +| `pc_artifact_lineage_sources`, locators, Artifact lineage, tags | Root input, system edit Source, base revision and tags; not mutable membership | +| `pc_artifact_processing_intents`, leases, binding state | Durable wakeup, explicit request generations, execution ownership and registration fences | +| `pc_artifact_search_states`, coverage, changes | Existing Scope/family build coordination and current-revision index maintenance | +| `pc_artifact_search_text`, vectors, vector spaces/index definitions | Fragment-level retrieval projections; `family=document`, `fragment_id=chunk_id` | + +Do not add `pc_rag_runtime`, per-rag generations/publications, a general jobs/receipts system, or separate nodes/directory +master tables. Do not store state in unrelated Scope settings or change Source payloads to simulate mutable metadata. +Document ownership is explicit, not inferred from tags or evidence lineage. + +The three supporting tables below are a proposed implementation baseline. Include UTC timestamps, byte-exact +identity comparison, bounded JSON metadata and backend-safe key lengths. Migrations must check actual layouts on +all three backends; equivalent existing storage may replace a table only with matching uniqueness and recovery semantics. + +| Table | Primary/unique keys | Minimum fields and role | | --- | --- | --- | -| `pc_rag_runtime` / rag | PK `(scope_id, rag_id)` | `state` (`active/disabled/deleted`), `version`, `effective_config_revision`, `active_generation_id`, `building_generation_id`, `change_seq`, `visibility_epoch`, `deleted_at`; operational state separate from content | -| `pc_rag_documents` / rag | PK `(scope_id, document_id)`; UQ `(scope_id, rag_id, namespace, external_key_hash)` | `rag_id`, full `external_key`, `state` (`active/deleted`), `target_source_type/id`, `target_content_generation`, `target_config_revision`, `last_change_seq`, `version`, `deleted_at`; identity reservation and membership | -| `pc_document_nodes` / document | PK `(scope_id, document_id, revision, node_id)` | `kind` (`section/block`), `parent_node_id`, `ordinal`, `title/text`, `source_locators`, `parser_metadata`; immutable evidence and hierarchy | -| `pc_document_chunks` / document | PK `(scope_id, document_id, revision, chunk_id)`; UQ `(scope_id, document_id, revision, ordinal)` | `section_id`, `text`, `content_digest`, `source_locators`, `origin`, `base_revision`, `edit_source_type/id`, `metadata`; complete effective snapshot | -| `pc_rag_index_generations` / rag | PK `(scope_id, rag_id, generation_id)` | `state` (`building/ready/active/retired/failed`), `config_revision`, immutable `profile_snapshot`, `start_seq`, `applied_seq`, `cutover_seq`, `build_fence`, `error`; independent profile builds | -| `pc_rag_document_publications` / rag | PK `(scope_id, rag_id, generation_id, document_id)` | `document_revision`, `target_content_generation`, `chunk_count`, `index_digest`, `version`; selects entirely indexed content, not membership or head | -| `pc_rag_jobs` / application service | PK `(scope_id, job_id)`; UQ `(scope_id, request_scope_key, operation, idempotency_key)` | `rag_id/document_id` where applicable, `binding_name`, `parent_job_id`, exact Source, `request_digest`, `profile_snapshot`, `target_content_generation`, `generation_id`, `change_seq`, `stage/state`, `attempt`, `lease_token/expires_at`, `next_attempt_at`, `receipt`, sanitized `error`, `actor`; receipts, item work, and index-change work | -| `pc_source_lifecycle` / shared Source service | PK `(scope_id, source_type, source_id)` | `state` (`active/deleted`), `delete_generation`, `deleted_at`, `deleted_by`, `reason`, `delete_operation_id`; initially used for document input and its edit Sources | -| `pc_rag_chunk_index` / rag adapter | PK `entry_id`; UQ `(scope_id, rag_id, generation_id, document_id, revision, chunk_id)` | Complete target key, `searchable_text`, `embedding_input_digest`, `vector_space_id`, `embedding`, `source_digest`; derived exact-chunk entries | - -`request_scope_key` is a server-generated, non-null canonical key: Scope+operation for rag creation, target rag -for its commands, or exact Source for deletion. Internal jobs use deterministic keys; nullable `rag_id` must not -weaken idempotency. The request digest covers operation, target, normalized input descriptor, and preconditions. -An accepted snapshot is pinned: retries return its receipt even if the original path changes. A new file version -requires a new request key. - -Store full external keys alongside fixed-size identity hashes; compare full values on collision and never silently -merge them. Import acceptance reserves the document ID and ownership row; the Artifact is created only after -processing succeeds, so a pending reservation cannot require a document-head foreign key. Content/node/chunk -references resolve to `(scope, family=document, document_id, revision)` and rag references to `family=rag`. -Use composite constraints or transactional validation for same-rag relationships. Public deletion has no SQL cascade. - -Manifests include root SourceRef, parser/OCR/chunker snapshot identifiers, `chunk_count`, `chunks_digest`, and schema -version. Chapter/block parent links stay in the same revision and are acyclic. Chunk locators refer to those blocks; -IDs and order are validated before publication. Edit Source payloads provide audit details without another master table. - -### 3.3. Indexes and backend mapping - -| Access path | Required index / invariant | -| --- | --- | -| List rag documents | `(scope_id, rag_id, state, document_id)` on membership; no full Scope Artifact scan | -| Read revision chunks | Unique ordinal index; keyset cursor fixes revision and last ordinal/chunk ID | -| Resolve Source dependencies | Reverse lineage index; retain root dependencies after every edit | -| Claim work / recover leases | `(binding_name, state, next_attempt_at, job_id)` and `(state, lease_expires_at)` | -| Catch up rebuild | `(scope_id, rag_id, change_seq)` on durable change jobs; retain receipts while builds need them | -| Search published content | Generation/publication keys and chunk-entry UQ; enforce exact revision before ranking | - -SQLite uses FTS5 with stable entry/row-ID mapping and a validated sqlite-vec adapter or another explicitly supported -exact-vector implementation. Missing vector capability must not silently downgrade hybrid requests. SeekDB and -OceanBase use separately verified full-text/vector adapters. `embedding` is a logical column: physical -dimension-specific tables or vector structures may differ, but map to the same exact chunk key. Check index-length -limits without truncating identities. Model/profile changes create generations rather than overwrite old vectors. - -A manual edit transaction writes its system Source, new manifest, complete nodes/chunks snapshot, lineage, target -generation, and index job while preserving membership. An index worker builds invisible entries, validates coverage -and digest, then compare-and-swaps the publication row. A full rebuild captures `change_seq` and applies durable -changes through cutover; inserts, updates, removals, and target changes advance it in their owning transaction. -Source deletion additionally checks the Scope visibility epoch before any per-rag fan-out finishes. - -Cancelled/superseded builds cannot become visible. First-phase retention includes deleted records and indexes; -storage therefore grows with revisions and rebuilds. Expose retained/visible counts and capacity failures. -Restoration, garbage collection, and permanent erasure are deferred, not implicit side effects of DELETE. - -## 4. Targeted asynchronous work and publication - -An import request fixes the Scope, target `rag`, exact SourceRef, logical document identity, processing configuration -snapshot, and input/request generation. Accepting or reusing a Source and recording target work must be atomic. -Source journal replay alone is insufficient: reuse in another `rag`, retries, and configuration rebuilds may append -no Source entry and must explicitly request processing. - -Reuse Scope/binding supervision, leases, timeouts, and execution fences. Workers claim persisted target work; -they do not broadcast every Source to every `rag`. The stages are parse/OCR, chunk/content commit, index build, -and publication. Each work item follows these transitions, with bounded retry policy: +| `pc_document_imports` | PK `(scope_id, document_id)`; UQ `(scope_id, rag_id, collection_id, path_hash)` | Full relative path, binding name, current/target SourceRef and digest, processing/configuration snapshot and fingerprint, target generation, operation (`import/reprocess/edit`), bounded pending edit, request ID/digest, state/stage, attempt, retry time, lease token/expiry, result revision and error; combines identity reservation, membership and latest per-file work | +| `pc_document_chunks` | PK `(scope_id, document_id, revision, chunk_id)`; UQ `(scope_id, document_id, revision, ordinal)` | Text, content digest, heading path, continuation/overlap metadata, normalized spans and original byte/image locators, origin, edit/base references; complete immutable revision snapshot | +| `pc_document_source_states` | PK `(scope_id, source_type, source_id)` | Immutable owner `rag_id`, document/file identity, `state=active/deleted`, deletion generation/time; mutable lifecycle alongside the original Source, including its system edit Sources | + +Reserve a document ID before parsing without requiring an Artifact head to exist. Once committed, all detail keys +resolve to `family=document` in the same Scope; each Source's owner matches the reservation and immutable payload. +The manifest contains owner rag, root SourceRef, schema/processing fingerprint, chunk count/digest and manual-change +indicator. A revision with 100 chunks has one manifest and 100 rows; removing a chunk creates a new manifest and 99 +rows without touching the original 100. Copies of unchanged rows may be prepared efficiently, but incomplete snapshots +must never become visible. Old revisions are addressed exactly, not by interpreting today's head. + +Index imports by `(scope, rag, document_id)`, pending work by binding/state/retry time, chunks by revision/ordinal, +and Source state by `(scope, rag, document_id)` for deletion fan-out. Verify existing reverse lineage access paths +for root-source revocation. Hash keys retain and compare full original identities. Source row ownership is immutable; +status/progress never changes it. The imports table preserves the latest target/result, not an unlimited batch or +command history. Errors before a Source is accepted belong to collection diagnostics. A complete durable batch +history would require an explicitly scoped extension, not an unbounded JSON array in a metadata row. + +## 5. Existing Workers and atomic content/index commit + +The application service coordinates the three plugins; it is not another plugin or service. Source acceptance/reuse, +Source lifecycle initialization, document target reservation/update, and `processing_intents.request()` commit +atomically. A durable target can therefore be recovered even if a wakeup notification is lost. The source-only +submission paths must call this same acceptance capability; they cannot bypass target validation. + +Supervisor dispatch remains Scope/binding based. The document processor selects pending import rows rather than +broadcasting every Source to every rag. Explicit requests handle retry/reprocess with no new Source journal entry; +do not fabricate a positive `source_through` or advance a Source cursor for target-only work. ```text -queued -> running -> succeeded - +--> retry_wait -> queued - +--> failed -queued / running / retry_wait -> cancelled or superseded -failed -> queued through an authorized explicit retry +pending -> running -> succeeded + +--> retry_wait -> pending + +--> failed / blocked +new target -> increment target generation; an old attempt becomes superseded +rag/document/Source deletion -> affected target cancelled; no further commit ``` -Expose stage, failure reason, attempt, and both latest-content and searchable revision. A first failure may have -no document Artifact yet. Retry the failed durable stage without duplicating content revisions or publication. -Replaying an idempotency key with a different request digest is a conflict. +Only one active target is processed per logical document. Identical pending input coalesces; a newer accepted file +version can supersede an older parse. Manual edits require no conflicting pending mutation. Persist the operation, +pinned input/configuration, base revision, and latest request token so restart can retry the same work. Replay of the +current token/digest returns current status; different content under that token conflicts. Superseded token versions +cannot recreate work. There is no promise of indefinite historical receipt replay. -| Boundary | Atomic records / required checks | +| Boundary | Work | | --- | --- | -| Snapshot preparation | Persist bytes before acceptance; failed acceptance may leave an unreferenced snapshot retained for a future GC policy | -| Import acceptance | Source acceptance/reuse, validated target request, and durable scheduling intent | -| Content commit | Complete manifest/details, provenance, validated membership, content receipt, and index work; manual edits also create their system Source here | -| Index publication | Verify complete indexes, exact content target, active configuration, execution ownership, and lifecycle; switch the searchable selection and visibility generation | -| Soft deletion | Persist owning lifecycle marker, advance visibility generation, and save idempotent receipt before acknowledgment; no physical cleanup | - -Run OCR, embeddings, DDL, and bulk index construction outside these short transactions. Every commit rechecks -registration/lease fences, target state, and input/configuration/deletion generations. A newer edit or import -supersedes old publication work. Durable work records are authoritative; process-local notifications only wake workers. - -Content head and searchable revision are distinct. Index failure preserves the previous published revision while -showing the new content and error. A `rag` rebuild uses a new generation and catches up accepted changes to a verified -cutover watermark before switching; a partially built generation cannot replace the active one. Rebuilding one -knowledge base cannot switch another's generation. Filesystem/database backup and restore must verify referenced -snapshots and index consistency before serving restored retrieval. - -Existing `pc_artifact_processing_pending.source_through` requires a positive Source position. Target-only work -uses requested intent generations and durable jobs without inventing a Source position or advancing a Source cursor. -Each claim captures its lease token plus Supervisor/binding fences; checkpoints compare all of them. Expired -ownership permits recovery but never authorizes a late worker to commit. - -## 5. Manual editing, reprocessing, and deletion - -Initially allow replacement of one existing chunk's text, guarded by the document head ETag. Do not expose chunk -insertion, deletion, merging, or reordering. Reject oversized edits rather than silently rechunking. Editing one -chunk does not silently edit overlapping text in another chunk. - -Follow Artifact management's provenance pattern: in the content transaction create a system Content Source with -`role=lineage_only` and `operation=artifact_replace`, then commit the new document revision and index work. Record -the base revision, edit, actor/reason, and exact target. This Source is not parsed again. Explicitly preserve the -original input Source dependency as well as the edit Source and base revision; generic replacement provenance -must not be assumed to retain the root input automatically. - -Manual replacement preserves logical chunk IDs, but citations always include revision. Reparse/rechunk generates -new chunk IDs; ordinal position is not identity. Edited results carry `origin=manual_edit` and `verbatim=false`: -their original locator is supporting evidence, not a claim that the edited words appear there. - -Updates refresh full-text entries, vector mappings, publication selection, and visibility-sensitive caches. -Embedding computation may be reused only when the complete actual input and model/profile identity match; -even then, new revision addresses must be indexed. Changing only embedding/index configuration preserves edited -content. Reprocessing manually edited content requires explicit `manual_edits_policy=discard`, otherwise a conflict. -Editing while a Source replacement/reparse is pending is rejected; editing committed content still being indexed -is allowed and supersedes older index work. Check these conditions atomically with target state. - -**The first release implements soft deletion only.** Keep Source payloads, original snapshots, document revisions, -chunks, edit evidence, and indexes physically stored. No restore or permanent-erasure endpoint is provided. -Deletion removes availability through supported application interfaces, not from backups or administrator storage -access. Retained tombstones prevent identity reuse and accidental resurrection. - -| Delete target | Authoritative marker | Immediate effect; retained objects | -| --- | --- | --- | -| Document Source | `pc_source_lifecycle.state=deleted` and Scope visibility epoch | All revisions rooted in it become unavailable, including manual edits across rags in that Scope; rag configuration remains | -| Document | `pc_rag_documents.state=deleted` and rag visibility/change counters | All its revisions/chunks become unavailable via membership, generic reads, and retrieval; Source and other documents remain | -| rag | `pc_rag_runtime.state=deleted` and rag visibility epoch | The knowledge base and its documents become unavailable; Scope, shared Sources, and other rags remain | - -Visibility is a conjunction, not a copied boolean on every row: ordinary content reads require a non-deleted, -enabled rag, active document membership, and non-deleted root Source. Search also requires active generation and -exact published revision. Historical reads can select older revisions but must check their parent/Source markers. -Resolve the root input from the requested revision, not the membership row's newest target Source. Historical -base-revision links are not transitive content dependencies: a fully reparsed replacement declares its own root. -Disabled rag configuration/status remain readable to authorized users; content retrieval is disabled. Re-enabling -a disabled rag does not restore a deleted rag. - -Source deletion needs no synchronous updates to every dependent chunk/membership row: the root marker and epoch -immediately reject reads. Administrative status derives the effective reason. Direct reads of system edit Sources -carrying derived text are gated through their exact document target and immutable root Source reference. Ordinary -Source, generic Artifact, history, chunk, raw-image, and cached reads cannot bypass these checks. -An original Source has its own Scope/lifecycle authority: deleting only a rag or document does not revoke that -Source or its direct original-file read. Edit Sources instead carry derived document text and must check their -document/rag target. Public Source DELETE targets original document inputs; edit Sources are system-managed. - -Keep lineage foreign keys and `RESTRICT` constraints: public DELETE physically deletes no Source/Artifact rows. -Repeated DELETE returns the accepted receipt without advancing counters again. Import into a deleted identity -returns `410`; a new identity must be explicitly chosen. No phase-one operation clears a deletion marker. -In-flight reads recheck visibility before returning; late workers fail commit/publication checks. Already delivered -responses cannot be recalled. - -Deleting an old Source does not revoke revisions derived solely from its replacement. A published old revision -rooted in the deleted Source becomes unavailable immediately, even while its replacement is indexing. Do not use -it as fallback, silently publish an unindexed replacement, or exempt manually edited content from Source checks. - -## 6. Retrieval and public interfaces - -Queries select complete `rag` references, in one Scope or across authorized Scopes. A Scope alone must not silently -select the first or all knowledge bases. Authorize every target and apply membership, metadata, lifecycle, -published-revision, and generation filters within each full-text/vector channel. Do not retrieve Scope-wide top-k -and filter afterward. If a backend cannot apply eligible-candidate filtering with ANN, use a verified filtered -exact-vector path rather than silently changing the retrieval contract. - -Use bounded candidate counts and deterministic rank fusion. Different embedding profiles require compatible -query embeddings; incompatible raw scores cannot be compared across knowledge bases. Deduplication preserves -distinct provenance. Return text, Scope/`rag`, document/revision/chunk, SourceRef, locator, edit markers, and actual -index profile/generation. Report per-target failures separately from no matches; all targets failing is a failure. -Parser, chunker, retrieval strategy, and optional reranking hooks must preserve these budgets and evidence contracts. - -Reuse generic Artifact create/read/replace/revision/tag shapes, complete references, pagination, errors, and -conditional writes. Add domain capabilities for targeted import, task inspection/retry, revision-pinned chunk -reads, chunk editing, retrieval, and Source revocation. Do not expose unrestricted generic document replacement -that can bypass provenance and ownership validation. Keep HTTP, Python client, and necessary MCP capabilities -consistent, with explicit knowledge-base context selection and unchanged Memory retrieval defaults. - -The following routes and payloads are proposed contracts. Implement them in `openapi/powercontext.yaml`, -generate clients, and run contract checks; they are not already available endpoints. -New families and detail tables require versioned migrations on all three backends; existing Sources and Artifact -families retain their contracts and are not automatically converted or enrolled in document processing. - -### 6.1. API surface - -Let `R = /v1/scopes/{scope_id}/artifacts/rag/{rag_id}` and -`D = /v1/scopes/{scope_id}/artifacts/document/{document_id}`. Routes below are proposed, not released. -Reuse current `ArtifactReference`, `ArtifactAddress`, `SourceTypeReference`, `ETag`, `Location`, pagination, -`ErrorResponse`, and Scope permissions. No parallel generic Artifact CRUD protocol is introduced. - -| Operation | Route / contract | Permission / response | +| Outside transaction | OpenDAL snapshot capture; parsing/OCR; Markdown/chunk construction; embedding and prepared index projections | +| Acceptance transaction | Validate owner/lifecycle and preconditions; accept/reuse Source and target state; request existing processing intent | +| Content transaction | Recheck target generation, base head, owner/Source lifecycle, plugin profile/build and Worker fences; commit manifest, complete chunks, lineage, any system edit Source, head, prepared indexes and successful target state together | +| Deletion transaction | Retire parent Artifact or mark Source deleted; invalidate the owned targets; record recoverable fan-out state using existing invocation plus target rows | + +Models and DDL do not run while holding the content transaction. The chunk projection adapter prepares from the +chunk snapshot rather than expanding the bounded manifest as if it contained full text; validate both snapshot +and projection fingerprints at commit. Existing generic JSON-field projection is not sufficient without this adapter. + +A failed normal update leaves the previous committed head and indexes; no new readable-but-unindexed revision is +created. History may be read independently but retrieval uses the current indexed revision. If the shared document +family index is rebuilding or unavailable, defer new document commits and expose unavailability. Do not silently +use the generic content-only-during-rebuild path, fall back to Memory retrieval, or promise zero-downtime cutover. +Rebuild reads committed chunks, not OCR again. SQLite, SeekDB and OceanBase must prove the transaction/read behavior +through their real adapters; native ANN limitations require filtered exact retrieval or an explicit capability failure. + +## 6. Editing, chunk removal, and soft deletion + +An edit command supports `replace_text` and `remove` for an existing chunk, with document `If-Match`. The worker +constructs a complete new revision, revalidates count/order/digest, prepares changed indexes, and commits atomically. +Deleting the last chunk is allowed: an empty effective document has zero indexed fragments but remains a readable +manifest with provenance. Unchanged chunks keep logical IDs; rechunking assigns new IDs. Every citation includes +revision. A remove operation affects the current snapshot only, never physically deletes historical chunk rows. + +At successful commit create the system Content Source with `role=lineage_only`, `operation=artifact_replace`, exact +new revision, base revision and edit/removal command. It records the modification and is not ordinary parser input. +Preserve the root document Source dependency explicitly; generic replacement does not imply this automatically. +Mark changed text `origin=manual_edit`, `verbatim=false`; original coordinates are edit evidence, not proof those +words occur in the image. Removing a chunk also counts as a manual change, protected against silent reparse overwrite. +Unchanged actual embedding input/profile may reuse computation, but new revision mappings still replace old entries. + +| Delete operation | Persisted state and consequences | +| --- | --- | +| Source | Mark sidecar state deleted without mutating payload. Retire a document whose current input is that Source; revoke all matching historical revisions and edit-Source reads. A current revision solely derived from a replacement Source survives | +| Document | Retire its Artifact head; block all its revisions/chunks and pending work; original Source is not deleted | +| rag | Retire its head, immediately block all owned content, then durably mark all owned Source versions and document heads deleted/retired, including documents that never finished processing | +| Chunk | Create a new document revision without that chunk; historical content stays intact | + +Retirement uses existing `lifecycle_state=retired` and governance CAS; do not add a second rag/document deletion flag. +Source deletion uses the sidecar because `pc_sources.payload` is immutable. Repeated deletion is idempotent. +A reserved document with no head is cancelled in its import row with terminal reason `document_deleted`; do not +create an empty Artifact just to retire it. That identity cannot be silently revived by another scan. Deleting a +pending replacement Source cancels its target but does not retire a committed revision based on a different Source. +Large cascades may finish in bounded batches: the retired rag and persistent ownership make incomplete fan-out +rediscoverable, while parent checks immediately prevent reads/commits. Source ownership is never shared across rags, +so deleting one rag cannot delete another's Source. Keep OpenDAL snapshots and canonical/historical content; do not +delete user files. Restore and permanent erasure are not offered initially. + +Search and generic exact/history/chunk reads check owner rag, document head and that revision's root Source. +Historical base-revision links do not make a fully reparsed replacement transitively dependent on an old Source. +System edit Sources also check their target document/rag. Original Source access checks its own state and owning +rag; deleting only a document leaves that original Source readable, deleting its rag does not. Family-specific read +validation must enforce these rules; generic retirement alone can otherwise leave exact reads available. + +Search indexes are derived, not historical evidence. Reuse their existing replacement/removal/rebuild maintenance; +soft deletion preserves business data, not a promise that every historical index entry is retained. Retained stale +entries must be excluded before ranking, including during cascade recovery. Parent/Source checks and commit fences +are mandatory regardless of physical index cleanup. Already delivered responses cannot be recalled. + +## 7. Unified API contract + +All routes below are design proposals or extensions; current schemas do not already support every family/filter. +Implement changes in `openapi/powercontext.yaml` and regenerate bindings. Reuse existing permissions, error envelopes, +Artifact/Source references, pagination, ETags and SDK/MCP operation mappings. Do not route document files through the +current generic create-Source command, whose schema only accepts built-in content; use the Source plugin protocol. + +Let `R=/v1/scopes/{s}/artifacts/rag/{r}` and `D=/v1/scopes/{s}/artifacts/document/{d}`. + +| Operation | Reuse or narrow extension | Semantics | | --- | --- | --- | -| Create rag | Existing POST `/v1/scopes/{s}/artifacts`, `family=rag`, typed `content`; extend this command with optional `idempotency_key` | `scope.contribute`; `201 ArtifactCreated`, ETag, Location | -| List/read/configure | Existing family list, GET/PUT `R`, revisions/tags; config PUT replaces complete content with current Artifact `If-Match` | Read: `scope.read`; config: `scope.contribute`; `200`, ETag | -| Operational state | New GET/PUT `R/runtime`; PUT accepts `enabled` and `expected_version`, without creating config revisions | Read: `scope.read`; control: `scope.admin`; `200` runtime version/state | -| Import batch | New POST `R/imports`; `idempotency_key`, items with unique `item_key`, namespace/key, and input descriptor | `scope.contribute`; `202` parent job and per-item receipts | -| Browse members | New GET `R/documents`; cursor/state filters, reserved targets, membership version, effective availability, head/published revisions | `scope.read`; `200 items/next_cursor` | -| Document/history | Existing GET `D` and revisions; manifest/provenance with lifecycle checks | `scope.read`; `200`, ETag | -| Chunk/evidence detail | New GET `D/revisions/{rev}/chunks` and `/nodes`; effective chunks versus original evidence; cursor/limit | `scope.read`; `200 items/next_cursor` pinned to revision/view | -| Edit chunk | New PATCH `D/chunks/{chunk_id}`; document `If-Match`, text/reason/idempotency key | `scope.contribute`; `202` new revision and index job | -| Reprocess document | New POST `D/reprocess`; document `If-Match`, idempotency key, explicit `manual_edits_policy=discard` when needed | `scope.contribute`; `202` job | -| Rebuild rag | New POST `R/rebuilds`; `config_revision`, `mode=index_only/reprocess`, idempotency key, edit-discard policy when needed | `scope.admin`; `202` generation/job | -| Inspect/retry work | New GET `/v1/scopes/{s}/rag-jobs/{job_id}`; POST `.../{job_id}/retry` with new idempotency key, same accepted target/input | Read: `scope.read`; retry: `scope.contribute`; `200` status / `202` receipt | -| Query selected rags | New POST `/v1/rag/query`; explicit targets, query, top_k, typed filters and bounded options | `scope.read` for every target; `200` hits and target outcomes | -| Original input | Existing Source GET returns descriptor; new GET `/v1/scopes/{s}/sources/{type}/{id}/content` streams the snapshot | `scope.read`; `200`, media type; no storage credentials | -| Soft-delete document | New DELETE `R/documents/{document_id}`, `expected_version` from membership | `scope.contribute`; `200` receipt | -| Soft-delete rag | New DELETE `R`, `expected_version` from runtime | `scope.admin`; `200` receipt | -| Soft-delete Source | New DELETE `/v1/scopes/{s}/sources/{type}/{id}`; restricted to document Source lifecycle initially | `scope.admin`; `200` receipt | - -DELETE carries `Idempotency-Key` and, where specified, an `expected_version` query parameter. Receipts contain -`operation_id`, target, `state=deleted`, `deleted_at`, and `data_retained=true`, without a cleanup job. Repeated -DELETE returns the original receipt. Administrative jobs can report deleted status without retained text; -normal content GET returns `410` after authorization. There is no `include_deleted` content bypass. - -Creating an empty rag atomically creates initial runtime/generation metadata without scheduling parsing. Config -PUT stores desired settings. Imports use effective settings; config changes do not silently reparse edited content. -Explicit rebuild activates the desired snapshot after verified cutover; `index_only` rejects parser/OCR/chunker -changes. Concurrent imports/edits remain durable and are caught up before switching. Expose desired and effective -revisions separately. Failed rebuilds leave the old effective configuration and indexes. -During ordinary document updates, a valid published revision need not equal the latest head or target generation. -That difference is intentional while indexing; only a successful publication switches it. Lifecycle revocation -always overrides this availability fallback. - -File input uses an authorized Source binding plus relative path, or an exact same-Scope `SourceTypeReference`. -Arbitrary client server paths, URLs, or snapshot locators confer no authority. The plugin captures bytes and validates -media/digest. Reusing a Source still schedules target work. Validate permission and batch shape before acceptance; -per-item capture failures may coexist with successes, but every accepted item atomically persists Source, identity -reservation, job, and intent. Report partial acceptance explicitly. Batch retries return the same item receipts; -failed capture without pinned input needs a new key, while worker retry uses the accepted snapshot. - -### 6.2. Representative payloads - -**Create** uses the existing `family + content` shape. Profiles below are illustrative configured bindings, not -hard-coded defaults. The rag content schema rejects unknown fields and contains no secrets or member arrays. +| Create/configure rag | Existing POST `/v1/scopes/{s}/artifacts`, GET/PUT `R`, revisions/tags | `family=rag`; complete config replacement and existing If-Match; no parser work for empty creation | +| Import directory/file | Existing POST `/v1/source-management/add` with discovered collect capability and instance | Plugin input carries owner rag and local root/file; Source receipt retains its existing collection semantics, not a new rag import/job envelope | +| Collection status/control | Existing source-management status and target/instance controls | Do not claim collect add reschedules a stopped target or status is full batch history | +| Sources/documents | Existing Source list/get; Artifact list/get/history | Add validated owner-rag filtering where missing; document GET returns bounded manifest, not all chunks | +| Current file progress | New GET `R/processing`, cursor and state filter | Latest per-file target, stage, attempts/error, request generation and committed revision, including unprocessed reservations | +| Retry/reprocess | New POST `D/processing`; failed first imports use reserved document ID even without a head | `action`, `expected_target_generation`, `request_id`, optional discard policy; `202` current target receipt | +| Read chunks | New GET `D/revisions/{rev}/chunks` | Existing items/next_cursor convention; exact-revision effective chunks and source locators | +| Edit/remove chunk | New POST `D/edits` | Document If-Match, bounded typed operation and request_id; `202` pending target, new revision only after atomic success | +| Retrieve | Existing POST `/v1/scopes/{s}/artifacts/document/search` | Existing query/mode/limit/fusion; required validated `filters.rag_ids`; extend optional matched fragments without replacing complete Artifact results | +| Soft-delete Artifact/Source | Add DELETE to existing exact Artifact/Source resource routes | Family writer/Source lifecycle service validates ownership; Artifact `expected_generation` (governance CAS); reuse scope.contribute for document, scope.admin for rag/Source | + +Rag config stores title/summary and parser/OCR/chunker settings or references, not runtime progress, members, or +main-path embedding configuration. A config change affects subsequent accepted targets; existing documents change +only through explicit reprocessing. Manual change protection still applies. + +Create example, using the standard Artifact envelope: ```json -{ - "family": "rag", - "idempotency_key": "create-ops-01", - "content": { - "schema_version": "1", - "title": "Operations SOPs", - "summary": "Runbooks and screenshots", - "profiles": { - "parser": "markdown-v1", - "ocr": "rapidocr-local-v1", - "chunker": "heading-paragraph-v1", - "embedding": "docs-embedding-v1", - "retrieval": "hybrid-v1" - } - } -} +{"family":"rag","content":{"title":"Operations SOPs","summary":"Runbooks and screenshots","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} ``` -**Import** into an existing rag uses exactly one input alternative per item: +Directory collection example; capability/instance names and settings are illustrative discovered deployment values: ```json -{ - "idempotency_key": "import-ops-01", - "items": [ - {"item_key": "a", "namespace": "oceanbase-docs", "external_key": "README.md", - "input": {"kind": "file", "binding_name": "local-documents", "path": "README.md"}}, - {"item_key": "b", "namespace": "ops-images", "external_key": "restart.png", - "input": {"kind": "source", "source": {"source_type": "knowledge-document-input", "source_id": "image-42"}}} - ] -} +{"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} ``` -The `202` result contains a stable parent job, per-item Source references and reserved document IDs, with -`document=null` until content exists. Parent counts distinguish acceptance from success. Item receipts expose -`stage=accepted/parse/chunk/index/publish`, state, attempt, latest-content/searchable revisions, and error. -Parent aggregation may report `partial_failure` without adding it to individual work-item states. +The target rag reference is validated at acceptance; ownership persists by rag ID, while processing pins accepted +configuration. A scan token is not a document identity and does not change the Source protocol's top-level schema. +A client retries a scan with the same token; a deliberate rescan uses a new one. -**Edit** PATCH `D/chunks/chunk-3` with the document GET's ETag in `If-Match`: +Chunk removal example, POST `D/edits` with the current document ETag: ```json -{"idempotency_key": "edit-03", "text": "Restart the follower before the leader.", "reason": "Correct OCR text"} +{"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} ``` ```json -{ - "document": {"family": "document", "artifact_id": "doc-1", "revision": 2}, - "index_job_id": "job-12", - "latest_content_revision": 2, - "searchable_revision": 1, - "chunk": {"chunk_id": "chunk-3", "origin": "manual_edit", "verbatim": false} -} +{"document_id":"doc-1","request_id":"edit-03","target_generation":4,"state":"pending","committed_revision":2} ``` -**Query** reuses `ArtifactAddress` for each rag. Target revision pins the config head seen by the caller; a stale -head returns conflict. The response separately identifies effective index/configuration, which may lag desired settings. +The receipt does not invent revision 3 before commit. GET processing later reports success and the committed new +revision, or failure with revision 2 unchanged. For replacement, use `kind=replace_text` plus `text`; do not represent +partial operations as complete content in generic PUT. Repeating the current request ID/digest reuses its target; +conflicting or superseded requests return conflict/precondition errors rather than silently reapply. + +Single-Scope retrieval reuses the generic request: ```json -{ - "targets": [ - {"scope_id": "project-p", "artifact": {"family": "rag", "artifact_id": "ops", "revision": 1}}, - {"scope_id": "project-q", "artifact": {"family": "rag", "artifact_id": "product", "revision": 3}} - ], - "query": "How should I restart a follower?", - "top_k": 10, - "filters": {"media_types": ["text/markdown", "image/png"]}, - "retrieval": {"mode": "hybrid", "candidate_limit": 100} -} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} ``` -Each hit carries Scope, rag/document ArtifactReferences, chunk ID/text/rank/score, SourceTypeReference, supported -locator data, origin/verbatim, and index generation. Return target statuses/errors and `partial`. Authorization -failure rejects the entire request before retrieval; an authorized target's operational failure may yield explicit -partial results. All-target failure remains an error. +`results` still contains complete document Artifact manifests and lineage. Add an optional typed `matches` field to +search items for bounded exact chunk hits: chunk ID, text, locator, origin/verbatim, and fragment scores. It is a +response projection, not part of persisted Artifact content. `limit` continues to bound returned Artifacts; +per-document fragment count has a separate capability limit. Validate only advertised document filters/options; +unsupported rerank is an explicit capability error. Neither unknown filters nor omitted rag selection may widen scope. -### 6.3. Errors, concurrency, and activation +For cross-Scope queries, the client/helper accepts explicit `(scope, rag)` targets, authorizes all of them, groups +calls to the same existing search operation and fuses ranks. Preserve document/chunk identity and per-target errors; +do not compare incompatible raw scores or silently return no matches on failure. This phase does not add a separate +`/rag/query` wire protocol. HTTP, Python and MCP use the same family operations, with bounded orchestration where needed. -| Condition | Contract | +| Condition | Response | | --- | --- | -| Same key/digest | Replay stable receipt after current authorization/lifecycle checks; deletion replays its tombstone receipt | -| Same key, different digest | `409 idempotency_conflict`, no new work | -| Missing/stale content or config ETag | Existing `428` / `412` precondition responses | -| Stale runtime/membership version, rag config, or pending reparse | `409` with machine-readable reason; no partial commit | -| Deleted target/evidence | `410 resource_deleted` after authorization; no text in error details | -| Unsupported input, invalid profile, oversized edit | `422`; transport byte-limit rejection may use `413` before acceptance | -| Missing backend/model capability | `503`, never an empty match list | -| Accepted asynchronous failure | Job becomes failed/retry_wait; `202` never means processing succeeded | +| Missing/stale document/config ETag | Existing 428/412 precondition errors | +| Conflicting target generation/request, pending edit or discarded-edit policy missing | 409 with actionable code | +| Deleted resource or evidence | 410 after authorization; no retained text in errors | +| Invalid format/config/oversized input | 422; transport may reject oversized bodies with 413 | +| Index/model unavailable or rebuilding | 503; no silent full-text-only downgrade or alternate-family search | +| Accepted processing fails | Latest target becomes failed/blocked/retry_wait; Source acceptance remains distinct from success | -Keep the existing error envelope: +Use the existing error shape, for example: ```json -{"error": {"code": "resource_deleted", "message": "The requested document is unavailable.", "details": null}} +{"error":{"code":"resource_deleted","message":"The requested document is unavailable.","details":null}} ``` -Content writes compare the document head; index writes compare exact target/publication versions. Both update -state and durable work atomically. Replay lookup precedes rechecking an old write precondition but never bypasses -current authorization/deletion. Failed commands roll back their receipts and writes. Staged content is invisible -until complete, and replay responses must not leak text from subsequently deleted targets. - -Migrations create schemas/indexes/capability declarations before activation. New document Sources get lifecycle -rows during acceptance; missing required lifecycle/ownership is an integrity failure, not permission to read. -Existing unrelated families remain unchanged. Reject activation without required backend/profile capability. -Validate upgrade/restart, duplicate requests, read-after-write, publication races, and deletion filters through -public APIs rather than direct table writes. - -## 7. Acceptance and delivery - -Use Markdown from a pinned `oceanbase/oceanbase` commit and standalone OCR fixtures with checked text/locators. -On SQLite, SeekDB, and OceanBase, verify: - -- Multiple empty knowledge bases per Scope, automatic document membership, exact citations, single-base filtering, - and explicitly authorized same-Scope/cross-Scope queries. -- Existing-Source reuse and idempotent retries, first-import failure without a document, process restart, atomic - content/membership/work commit, and failed indexing with an old searchable revision. -- Real RapidOCR execution, malformed/unsupported input and no-text outcomes, preserved Markdown image references, - and full-text/vector retrieval over document chunks without whole-document JSON scans. -- Manual edit provenance, complete snapshots, revision-pinned pagination, updated full-text/vector mappings, - reparse conflicts, stale-worker rejection, and generation cutover during concurrent updates. -- Source/document/rag soft deletion, historical/cache/original/edit-Source read enforcement, retained physical rows, - idempotent deletion, and preservation of unrelated documents, replacement-Source revisions, and rag configurations. - -Use existing issues for delivery: #2441 covers foundations/ingestion, #2442 processing/content/index lifecycle, -#2443 retrieval/interfaces, and #2444 operational visibility and cross-backend acceptance. The implementation can -use one integration branch and PR with these four review stages. This RFC PR completes none of those implementation -issues. Publish supported formats, model versions, resource limits, and recovery instructions with implementation; -do not infer production capacity from functional fixtures. +## 8. Implementation and acceptance + +Framework reuse still requires a typed document Source acceptance hook, per-file selection in Workers, a +chunk-backed projection adapter, filtered retrieval before top-k, lifecycle checks on all reads, and same-transaction +family writers. Reuse tables does not justify storing full documents in manifests or treating generic JSON projection +as already sufficient. No changes to core metadata columns are planned; additive domain migrations and OpenAPI +extensions must be reviewed if the implementation discovers a genuine gap. + +On each of SQLite, SeekDB and OceanBase, test the following through public operations: + +- Create two rags in one Scope and another in a different Scope; same file imports have exclusive owners and no query leakage. +- Capture Markdown from a pinned `oceanbase/oceanbase` commit and real OCR fixtures; preserve image references and accurate locators. +- Identical success skips, failed identical input retries, changed bytes revise, config changes reprocess, and embedding-only changes do not OCR. +- Reject stale workers and conflicting edits; restart from durable current targets; content/index failure exposes no half-published revision. +- Delete a chunk by revision replacement, including the last chunk; old snapshots remain complete and current indexes exclude it. +- Source/document/rag soft deletion, cascading completion after restart, historical/edit-Source read checks, and new-Source revisions surviving old-Source deletion. +- Plugin config initialization from compatible main settings without live coupling; isolated indexes and explicit unavailable rebuild behavior. +- Core schema compatibility, filtered hybrid search, pagination and contract generation; mocks alone do not establish real backend/OCR support. + +Use existing #2441 for ownership/ingestion, #2442 for processing/content/index integration, #2443 for retrieval/interfaces, +and #2444 for diagnostics/three-backend acceptance. One implementation branch/PR may deliver these four review stages. +This RFC PR does not close implementation issues. Do not add issues or claim large-corpus capacity from functional fixtures. # Drawbacks -Complete snapshots amplify storage and write cost even for a one-chunk edit. Separating content and searchable -revisions complicates reads and diagnostics. Dedicated consumer restrictions, target work, family writers, and -revocation need framework integration beyond a plugin declaration. Three backends add migration and index testing -cost. RapidOCR model packaging and platform compatibility also require explicit maintenance. Soft deletion retains -all data and indexes, so it is not an erasure feature and requires storage-capacity monitoring. +Complete chunk snapshots amplify storage and writes. Retaining soft-deleted originals/history requires capacity +monitoring. Shared document-family rebuilds can interrupt retrieval across rags in one Scope. Latest per-file state +is simpler than a task center but lacks complete batch/command history. Plugin-specific read/projection/acceptance +integration is still substantive work even with unchanged core schemas. OCR packaging/platform support needs testing. # Rationale and alternatives -- **A Scope per knowledge base:** provides existing isolation but couples collection organization to authorization - and project identity. Multiple `rag` Artifacts keep those concerns separate; use separate Scopes when isolation is required. -- **Chunks stored in mutable Sources:** mixes original evidence with derived content and conflicts with Source immutability. -- **One Artifact per chunk:** turns a whole-document update into many independent Artifact lifecycles and obscures atomic revisions. -- **All chunks in one Artifact JSON field:** simplifies writes but makes passage reads and indexing depend on large payloads. -- **Independent knowledge-base master tables:** duplicate existing Artifact identity, version, and management facilities. -- **Source-journal-only generation:** cannot reliably express empty `rag` creation or work triggered by existing-Source reuse. - -The selected design preserves whole-document identity while giving chunks efficient physical storage and explicit -publication. Doing nothing leaves applications to assemble inconsistent ingestion, provenance, and deletion workflows. +- A Scope per knowledge base couples collection organization to authorization; multiple rag Artifacts preserve project grouping. +- Sharing one logical Source across rags makes deleting a rag affect others; share only physical snapshot bytes if desired. +- Storing chunks in Sources violates immutable evidence; one Artifact per chunk obscures whole-document revision semantics. +- Whole-document JSON arrays simplify serialization but make retrieval/detail reads unnecessarily large. +- Separate rag runtime, publication generations and general job tables support advanced features but are unnecessary for atomic revision/index commits. +- Direct SQL deletion of a chunk breaks old revision counts, digests and citations; revision replacement preserves evidence. +- A live fallback to main-path embedding settings can silently change vector space; plugin-owned resolved configuration avoids it. # Prior art -This proposal builds on the repository's [Source plugin design](2012-source-plugin-system.md), -[Artifact plugin design](2175-artifact-plugin-system.md), [Source model](1400_source_definition_and_observation_model.md), -[Artifact processing supervisor](1515_artifact_processing_supervisor.md), -[Source/Artifact API](1437_source_artifact_rest_api.md), and [Topic Memory](1417_topic_memory.md). -It reuses their extension, provenance, scheduling, and read boundaries while adding explicit collection management -and document-specific storage/publication. Topic Memory's family-specific detail/index schema is not a shared document schema. +Build on [Source plugins](2012-source-plugin-system.md), [Artifact plugins](2175-artifact-plugin-system.md), +[Source identity](1400_source_definition_and_observation_model.md), [processing supervision](1515_artifact_processing_supervisor.md), +and [Source/Artifact APIs](1437_source_artifact_rest_api.md). Existing OpenDAL capture already compares path/content hashes; +Artifact head governance and generic fragment indexes provide reuse foundations, not a complete knowledge-base implementation. +Atomic Memory retirement is a useful lifecycle pattern but is not already a Source-to-document cascade contract. # Unresolved questions -The following must be fixed and tested in the implementing changes; they do not defer identity, atomicity, -consumer restrictions, or revocation semantics: - -- Exact Python capability/writer signatures, migration DDL, and backend layouts implementing the contracts above. -- Limits for snapshots, decoded image pixels, manifests, chunks, pages, worker concurrency, timeouts, and retries. -- Pinned RapidOCR/ONNX/model versions, supported image formats/platforms, and default chunk/embedding profiles. -- Future retention/erasure policies and expired-reference responses; phase one retains historical and soft-deleted data. +Implementation must fix precise capability signatures, supported image formats/model versions, resource limits, +backend migrations/transaction behavior, and defaults validated against actual embedding token limits. The three-table +baseline must be verified rather than expanded preemptively. Any core schema change needs a demonstrated gap and review. -Full edited-document export needs an explicit overlap and edit reconciliation contract. Independent per-`rag` ACLs, -cross-deployment federation, and shared document ownership require separate design work rather than implicit support. Restoration and permanent -erasure also need explicit dependency, authorization, and audit rules before exposure. +Permanent erasure, restoration, retention/GC, renamed-file identity, complete batch history, independent per-rag +embedding/rebuilds and full edited-Markdown export need separate contracts. Overlapping chunks cannot simply be +concatenated into an accurate edited document. # Future possibilities -Additional parsers, storage providers, automatic collection, alternative chunkers, rerankers, and bounded agentic -retrieval can use the declared component boundaries. Measured storage pressure may justify shared immutable chunk -bodies across revisions. These extensions must preserve exact evidence, target isolation, and publication/deletion -semantics; they are not prerequisites for the initial knowledge-base workflow. +Additional OpenDAL providers, parsers, richer chunkers, rerankers and bounded agentic retrieval may extend the component +boundaries. Measured storage pressure may justify shared immutable chunk bodies. None is required for first-phase +ownership, duplicate detection, atomic commits or exact evidence. diff --git a/docs/zh/rfcs/2570-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md index dd4caeacbb..d71022a6ed 100644 --- a/docs/zh/rfcs/2570-rag-knowledge-base.md +++ b/docs/zh/rfcs/2570-rag-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570:基于 rag Artifact 的文档知识库" -description: "通过插件实现文档知识库,保留不可变 Source、分块版本、混合检索与可恢复的后台处理。" +description: "复用 Source、Artifact 和后台处理设施,通过 OpenDAL 接入文档、简单 Markdown 切块和插件独立检索配置构建知识库。" --- - Proposal Name: `rag_knowledge_base` @@ -11,477 +11,371 @@ description: "通过插件实现文档知识库,保留不可变 Source、分 # 概述 -通过一个文档 Source 插件和 `document`、`rag` 两种 Artifact family 提供文档知识库。一个 Scope 内允许用户创建多个 -`rag` Artifact。用户向指定 `rag` 导入文件,后台解析不可变输入,生成代表整篇文档、分行保存 chunks 的 document Artifact, -自动关联知识库,再发布全文/向量索引。本文描述设计目标,不表示接口已经发布。 +通过文档 Source 插件和 document、rag 两个 Artifact family 提供知识库。一个 Scope 可有多个用户创建的 rag, +每个文档 Source 和 document 唯一归属一个 rag。OpenDAL 采集本地文件,Markdown 与图片 OCR 共用简单 Markdown 切块策略, +复用 Artifact Worker,在内容和索引准备好后一起提交 document revision。复用核心元数据表结构、CRUD、监督和通用索引存储, +仅增加文档明细与目标记录。本文是建议契约,不表示功能已发布。 # 动机 -业务描述和任务 SOP 需要带精确证据的片段检索,以及显式更新和删除能力。提取的记忆可以补充这一场景,但不能保留全部文档内容。 -知识库必须区分原始输入、处理后的内容和可检索版本,避免处理失败破坏已有结果,也避免把人工纠正伪装成原始证据。 +业务描述和 SOP 需要完整文档的片段检索、精确出处、显式更新和可预测的删除行为。记忆提取无法保留每个片段。 +首期应覆盖这条流程,不另建任务平台、逐 rag 索引代次系统或重复 Artifact 主表。 -复用 PowerContext 的 Source 定义、Artifact 管理、插件注册、Scope 授权、处理监督和持久化设施,补充其中尚缺的文档专用契约, -不另建平行的知识库对象体系或通用工作流引擎。 +Source 快照和历史 document revision 是证据,知识库检索是派生投影,与 Memory 检索数据和默认配置隔离。 +复用基础设施,但不能把现有插件声明视为已具备定向导入、分行 chunk 存储和删除校验的全部能力。 # 使用层说明 -Scope 继续代表项目或工作空间,并作为首期授权边界。知识库是 Scope 内的 `rag` Artifact,拥有独立名称和处理/检索配置。 -知识库改名或删除不会改变 Scope。一个 Scope 内的不同知识库不构成独立的保密边界。 +1. 在已有 Scope 中通过通用 Artifact 创建 rag。 +2. 选择 rag 和本地目录/文件,客户端使用配置好的本地 OpenDAL Source 插件;用户无需提供 Source ID、namespace、hash 或 document ID。 +3. 查看逐文件最新处理状态,输入已接受不代表内容可检索。 +4. 检索指定 rag 的文档,或显式选择多个已授权 rag。 +5. 修改文件后再次导入:相同且已处理成功的输入跳过,内容变化生成新 Source 和同一 document 的新 revision。 +6. 编辑或删除 chunk 都生成新 document revision,旧 revision 及其 chunk 内容保持完整。 -例如,团队在同一 Scope 中创建“产品文档”和“运维 SOP”: +Scope 仍是授权边界。Source/document 独占归属 rag,不跨库共享逻辑身份。同文件导入两个 rag 会产生不同 Source/document, +底层快照可按实际需要去重。首期支持 Markdown 和独立导入的文字图片,OCR 使用 RapidOCR + ONNX Runtime。 +Markdown 内图片仅保留引用,不抓取、不自动 OCR。SQLite、SeekDB、OceanBase 均须支持完整流程,一个部署选择一种持久化后端。 -1. 通过 Artifact 管理创建两个空 `rag`,无需先导入文档。 -2. 向“产品文档”导入 Markdown,向“运维 SOP”导入独立的文字图片。 -3. 获取持久导入回执,查看解析、索引和失败状态。 -4. 检索单个知识库,或显式选择两个库联合检索。处理后文档自动关联知识库,索引发布后才能检索,无需手动挂载 document。 -5. 替换原文件或编辑已有 chunk,生成新 document revision;索引就绪后新内容参与检索。更新失败时保留旧发布版本,除非它已被撤销或移除。 - -首期支持 Markdown 和独立导入的图片,OCR 使用 RapidOCR + ONNX Runtime。Markdown 图片仅保留引用,不抓取或识别引用目标。 -SQLite、SeekDB、OceanBase 均须支持完整功能链路;一个部署使用其中一种后端。 - -普通 TXT、PDF、Office、自动同步、生产级 rerank、agentic 检索、完整管理界面和几万篇文档的规模评测不作为首期验收条件。 -但任务状态和恢复 API 必须能支撑后续界面。根据检索结果回答问题仍由应用负责。 +PDF、Office、普通 TXT 导入、语义/LLM 切块、复杂版面/表格重建、定时目录同步、每 rag 独立 embedding 空间、 +单库独立无停机索引切换、完整管理界面和大规模语料性能门槛不属于首期。后续界面使用逐文件状态契约。 # 技术说明 -## 1. 身份、归属与溯源 +## 1. 归属与插件配置 ```text Scope - +-- rag K1 -- 成员关系 --> document D1 -- revisions --> chunks - +-- rag K2 -- 成员关系 --> document D2 -- revisions --> chunks - ^ -不可变文档 Source ---------------+ 内容溯源 + +-- rag K1 -- 拥有 --> 原始 Sources -- 派生 --> document revisions -- chunks + +-- rag K2 -- 拥有 --> 独立 Sources/documents,即使本地文件相同 + +Source 插件:OpenDAL 采集与不可变快照读取 +Document 插件:Markdown / OCR -> Markdown -> chunks、内容版本和溯源 +rag 插件:集合管理、检索策略和索引适配 +共享设施:Source/Artifact API、Supervisor/Worker、事务、数据库/搜索适配 ``` -| 对象 | 身份与职责 | -| --- | --- | -| `rag` Artifact | 用户创建的配置与集合身份;成员变化和处理进度不生成配置 revision | -| 文档 Source | 不可变原始输入描述:原路径、受管理快照引用、摘要、媒体类型和采集元数据 | -| `document` Artifact | 一篇完整逻辑文档,ID 稳定,内容 revision 递增;首期唯一归属一个 `rag` | -| Chunk | document revision 内部的内容和检索单元,不是 Source 或独立 Artifact | -| 索引 generation | 以 `rag` 为范围的索引配置/构建,与内容 revision、插件注册代次分离 | +rag 是配置和集合身份,不是消费 Source 生成的结果,可以为空。名称/配置使用 Artifact revision,删除使用现有 head 治理状态。 +不另设 rag 运行状态表或运行状态 API。解析进度属于导入文件,不生成 rag 配置 revision。 -逻辑文档身份为 `(scope, rag, source_namespace, external_key)`。同一身份再次导入更新原 document;同路径导入另一 `rag` -产生独立 document,不能按内容摘要合并逻辑身份。一个不可变 Source 可显式复用于同 Scope 的多个知识库,但不因此建立跨 Scope -Source 身份或共享 document 归属。 +document 代表整篇文档,稳定身份范围为 `(scope, rag, collection, relative_path)`,chunks 是 revision 内部明细。 +collection 由系统根据注册的存储 binding/instance 和规范化根目录生成,不使用每次变化的扫描 ID。 +Source payload 保存不可变的所属 rag、原路径、相对路径、媒体类型、内容摘要和受管理快照引用。任务固定处理配置快照, +可变状态和解析结果不写回 Source。专用 Source 仅供 document 链路直接消费,在选择、执行、提交时都校验。 -Source lineage、`rag` 成员关系和可检索 revision 选择是三种不同关系,不能用标签代替归属。原路径用于溯源,读取使用采集时的 -不可变快照,而非路径现在指向的文件。原始 Markdown 字节和图片保存在 OpenDAL 管理的本地目录,适当复用现有 OpenDAL/`opendalfs` 集成。 +三个逻辑插件可在一个安装包中交付。知识库插件包独立管理 embedding/索引配置,与 Memory 等主路径分离。 +显式插件配置优先;未指定时,可在安装时用主路径的兼容值初始化并保存解析后的配置快照。保存凭据引用,不把密钥复制进 Artifact。 +之后主路径配置改变,不静默改变插件 profile。配置缺失或不兼容则拒绝启用。 +Parser/chunker 可按 rag 配置,首期 embedding/索引为插件级配置,在各 Scope 的 document family 内共用。 -定义专用文档 Source 类型,暂称 `knowledge-document-input`,仅允许 document 处理链路直接消费。在输入选择、执行和提交校验中 -落实限制,不仅靠命名约定;不能自动将其暴露到其他 Artifact family 消费的通用证据流。解析结果、OCR 文字、chunks、索引指针和 -任务进度不得回写 Source payload。 +可以复用模型调用和 SQL 适配代码,但按 family、索引定义、向量空间/profile 身份隔离,查询不隐式混入 Memory 数据。 +插件模型/维度变化沿用现有 family 重建机制及其可用性限制,不新增逐 rag 发布协议。 -## 2. 插件职责与框架适配 +## 2. OpenDAL 导入与重复判断 -| 逻辑插件 | 负责的行为 | -| --- | --- | -| 文档 Source | 文件校验、不可变快照、Source 接受、授权后的原文读取 | -| `document` Artifact | 解析、OCR、切块、内容版本、chunk 读取、人工编辑和证据映射 | -| `rag` Artifact | 配置、成员关系、索引 generation、发布、混合检索和显式多库查询 | +通过现有 OpenDAL/opendalfs 集成列举和读取本地文件。插件 instance 必须运行在所选路径实际存在的机器上, +远端 Server 不能将客户端本地路径当作自己的文件。相对路径在配置根目录下解析,拒绝越界,路径规范化和符号链接策略保持稳定。 +接受 Source 前将原始 Markdown 字节/图片保存成受管理不可变快照。对实际保存的字节计算 hash,不能对第一次读取算 hash、 +再处理已经变化的第二次读取。读取失败或检测到采集不稳定时允许重试。 -这是三个逻辑插件,不要求三个进程或独立安装包。Parser/OCR/chunker 是 document 内的可替换组件;索引和检索适配归 rag, -使用共享数据库和模型设施。rag 可以引用默认配置,组件 schema 由其所属能力校验。 +```text +file_key = (scope_id, rag_id, collection_id, normalized_relative_path) +content_digest = SHA256(采集到的原始字节) +source_key = hash(Source schema 版本, file_key, content_digest) +processing_key = hash(content_digest, parser/OCR/model 版本及配置, + Markdown 规范化版本, chunker 版本及参数) +index_key = hash(完整 embedding 输入, 插件 profile 和投影版本) +``` -复用 Source、Artifact 插件注册及现有管理/读取约定。现有生成模型仍需扩展显式 rag 创建、领域明细存储和定向任务能力: -空 rag 是管理对象,不是消费 Source 的生成结果。不能伪造输入 Source 来触发建库,也不能声称仅配置通用插件声明就已满足全部能力。 -仍可记录现有系统生成的管理溯源,但不触发文档处理。 +mtime/大小可辅助选择工作,但不能证明内容相同。hash 碰撞时比较完整身份,不能截断路径或仅按摘要合并文档。 +用户可见 Source ID 由框架结合插件的确定性身份规则生成。复用已有不可变 Source 时保留第一次 canonical 采集元数据, +不覆写 mtime 或注释。 -知识库应用服务通过注册的 family 能力协调这些操作,不是第四个领域插件。各 writer 只管理本领域记录,并参与调用方共享数据库事务; -插件不能写其他插件的私有表或独立提交。首期使用同一部署数据库,不做插件服务间的分布式事务。document parser 无权决定目标 rag。 +| 观察结果 | 处理规则 | +| --- | --- | +| 同文件/内容/处理指纹,已有成功结果 | 复用 Source 和 document,不生成新 revision;另查索引是否就绪 | +| 相同目标正在等待/运行 | 合并到现有目标,不重复解析 | +| 输入相同,但上次处理失败 | 保留固定 Source,允许有界重试;采集 checkpoint 不等于处理成功 | +| 同路径,字节变化 | 新增 Source,生成同一 document 的新 revision | +| 字节相同,parser/OCR/chunker 变化 | 复用 Source,显式重处理并生成新 revision | +| 仅 embedding/索引 profile 变化 | 使用已提交 chunks 重建,不再次 OCR | +| 路径或 rag 不同,字节相同 | 不同逻辑文档和 Source,仅可复用物理快照 | +| 遇到已删除身份 | 不自动恢复;首期无恢复接口,需显式采用新身份 | -## 3. 解析与 chunk 存储 +文件恢复到曾经出现过的字节时,也要比较当前目标/结果;找到旧 Source 不代表当前 document 已是该内容。 +首期改名按新路径处理,文件消失不隐含删除。相同文件重扫不能覆盖人工编辑/移除。 +含人工修改的文档遇到输入变化或显式重处理时,要求 manual_edits_policy=discard,否则保留旧提交版本并报告可操作的冲突。 +原始输入 Source 可以已经采集,但内容处理仍保持阻塞。 -Markdown 使用 `markdown-it-py` 处理,保留标题、段落、列表、代码、表格和链接。将解析位置映射回原始 UTF-8 字节,不能用块级行号 -伪造行内精确位置。RapidOCR + ONNX Runtime 处理独立图片,固定模型身份、限制图片大小,并将预处理后的坐标映射回原图。 -保留真实 OCR 文字、置信度和区域;区分不支持的输入、非法编码、坏图、无识别文字、模型缺失和超时,不用生成模型补写或改写 OCR 输出。 +目录导入复用 Source collect 能力发现和现有 add/status/control 操作。客户端在插件 input 中生成 scan_token, +标识一次显式扫描目标。同 input 重试 add 复用目标;用户再次导入使用新 token,但 collection/file 身份不变。 +插件每 token 只扫描一次,并继续等待后续目标,不定时重扫。现有 Source status 表示采集状态,不是完整文档处理或批次历史。 +新扫描必须同时检查文档处理状态和采集 checkpoint,避免“采集未变”掩盖下游失败。 -两条路径都输出经过校验的 blocks、sections 和原文定位,交给可配置的标题/段落/长度切块策略。保留顺序、重叠/续块关系、邻接信息, -以及可能包含多个原文跨度或图片区域的定位。定位必须对应真实证据;OCR 置信度是引擎分数,不是准确率承诺。 +## 3. Markdown 规范化与简单切块 -| 存储 | 建议表示 | -| --- | --- | -| 现有 Artifact 记录与 heads | 每个 document revision 一条有界 manifest:标题/摘要、原始 Source 引用、配置标识、schema 版本、chunk 数量和集合摘要 | -| 文档明细 | 每 chunk 一行,以 `(scope, document_id, revision, chunk_id)` 为键,配套章节/block 结构和证据/编辑元数据 | -| 成员与目标状态 | rag 归属、逻辑文档键、目标输入/配置,以及生命周期和并发代次 | -| 检索投影 | chunk 级全文/向量条目及精确 revision/profile/generation 映射 | -| 处理记录 | 持久目标请求、阶段/结果、重试、租约及可恢复的索引工作与删除回执 | +两种输入形成统一 Markdown 视图: -在语义匹配时复用 Artifact、head、lineage、tag 和处理设施。不新增重复的知识库/document/revision 主表,也不将文档数据混入 -Topic Memory 专属 chunk 表。下述建议结构确定归属、键和最小字段;后端 DDL 和辅助索引通过迁移落实,不在运行时临时建表。 +```text +Markdown 字节 -> markdown-it-py 结构/原文字节映射 ---+ + +-> 规则切块 +图片 -> RapidOCR -> 文字行/区域 -> 规范化 Markdown --+ +``` -首期每个 revision 保存**完整 chunk 快照**。100 块的文档保存一条 manifest 和 100 行明细;编辑一个块后再保存一条 manifest -和完整 100 行快照。校验数量、唯一顺序、结构引用,以及覆盖有效文本、顺序和证据映射的摘要。分批暂存数据在完整 revision 提交前不可见。 -这一选择接受存储放大,以简化版本读取和恢复;跨 revision 共享 chunk 正文留待后续。 +OCR 保留真实文字、顺序、置信度和原图区域,考虑预处理坐标变换。Markdown 转换只做语法转义、文字行/段落组织, +不猜标题、不用 LLM 修正文案、不重建复杂表格。保留规范化文字跨度到 OCR 行和原图区域的映射。 +规范化 Markdown 是派生内容,不能替代图片 Source;定位必须说明真实精度。 -Artifact 主体不能保存无界的全文/chunk/向量数组。检索直接访问 chunk 索引,再批量读取精确命中和同版本邻接块。通用 Artifact -读取返回 manifest;明细分页游标固定 revision、视图和顺序。原始解析证据与编辑后的有效 chunks 分开读取,不能直接拼接重叠 chunks -来导出编辑后的整篇文档。 +按标题、段落、列表和代码块处理,合并短块直到接近 max_chunk_chars,超长块再按句子/长度拆开, +必要时在拆分边界保留 overlap_chars,并校验 overlap 小于最大长度。保留标题路径、顺序和续块标记,不建设独立章节树系统。 +Embedding 前还要检查真实模型 token 预算,包括标题/前缀上下文,不静默截断。改变边界的切块配置变化需要版本化。 -### 3.1. 复用的现有表 +媒体校验、非法 UTF-8、损坏/不支持图片、无识别文字、模型缺失、像素超限和超时分别处理,固定并验证真实 RapidOCR、ONNX 和模型版本。 +规范化 Markdown 可以在处理期间计算,首期不要求独立解析缓存。Chunks 保存有效文字和有界来源映射,不保存向量。 +Artifact manifest 有界,不嵌入全部 chunks。 -| 现有表/设施 | 用途与必要适配 | -| --- | --- | -| `pc_sources`、`pc_source_journal_heads` | 保持 canonical payload 和 journal 顺序不可变;引用原始快照,不保存派生 chunks | -| `pc_artifacts`、`pc_artifact_heads` | 保存 rag 配置、document manifest 和版本;所有 Artifact 键保留 family;head 不作为检索发布指针 | -| `pc_artifact_lineage_sources`、`pc_artifact_source_locators` | 保留原始输入和编辑 Source;增加/核实 `(scope_id, source_type, source_id)` 反向查询索引 | -| `pc_artifact_lineage_artifacts` 与 tags | 精确 base revision 证据和标签,不代表 rag 成员关系 | -| `pc_artifact_processing_intents`、租约与 binding 状态 | 复用唤醒、执行资格和注册栅栏,逐文档工作单独记录 | -| `pc_scope_settings` | 保留系统管理的 Source 可见代次,和 Source 删除原子递增;不允许用户直接修改 | +## 4. 持久化:核心表结构不变,三张支撑表 -不复用 `pc_artifact_publications` 表示可检索版本,它负责跨 Scope 发布。通用搜索状态按 Scope/family 标识,未经扩展不能支持 -两个 rag 各自的 generation。可复用向量空间定义和适配代码,但 rag 发布选择必须独立;通用 head 的 searchable_text 不是片段索引。 +本方案不修改现有核心元数据表定义。新 family 记录、声明和索引沿用既有 schema,这是迁移约束,不代表无需修改处理代码。 -### 3.2. 建议关系表结构 +| 复用设施 | 用途与必要代码适配 | +| --- | --- | +| `pc_sources`、Source journal、connector checkpoints | 不可变输入、采集身份和采集进度 | +| `pc_artifacts`、`pc_artifact_heads` | rag 配置、document revision manifest、active/retired 状态和治理 CAS | +| `pc_artifact_lineage_sources`、locators、Artifact lineage、tags | 原始输入、系统编辑 Source、base revision 和标签,不表示可变成员关系 | +| `pc_artifact_processing_intents`、租约、binding 状态 | 持久唤醒、显式请求代次、执行资格和注册栅栏 | +| `pc_artifact_search_states`、coverage、changes | 现有 Scope/family 构建协调及当前版本索引维护 | +| `pc_artifact_search_text`、vectors、向量空间/索引定义 | 片段级检索投影,family=document、fragment_id=chunk_id | -以下是拟定表名,不表示现有数据库已经包含这些表。基线为七张领域表、一张共享 Source 生命周期表和一张 chunk 索引投影表。 -不重复新增 Source/Artifact/revision 主表,不另建编辑审计表和请求回执表。只有保持下述键、原子性和读取行为时,才能合并到 -语义等价的既有设施中。后端搜索结构可能额外需要物理表。 +不新增 pc_rag_runtime、逐 rag generation/publication、通用 jobs/receipts 系统、独立 nodes/目录主表。 +不把状态塞进无关 Scope settings,也不改 Source payload 模拟可变元数据。文档归属必须显式,不能从标签或证据 lineage 推测。 -所有键和关联包含 scope_id。ID 按字节精确比较,revision 为正整数,代次为非负大整数,时间使用 UTC。 -PK 表示主键,UQ 表示唯一键;省略公共时间字段。JSON 仅存有界元数据/配置,不保存整篇文档的 chunk 数组。 +以下三张支撑表是建议实现基线。使用 UTC 时间、字节精确身份比较、有界 JSON 和满足各后端限制的键长度。 +迁移必须核实三个后端的实际布局;只有唯一性和恢复语义相同时才能用既有存储替代。 -| 建议表/所属能力 | 键 | 最小字段与用途 | +| 表 | 主键/唯一键 | 最小字段与职责 | | --- | --- | --- | -| `pc_rag_runtime`/rag | PK `(scope_id, rag_id)` | `state`(active/disabled/deleted)、`version`、`effective_config_revision`、`active_generation_id`、`building_generation_id`、`change_seq`、`visibility_epoch`、`deleted_at`;运行状态与内容分离 | -| `pc_rag_documents`/rag | PK `(scope_id, document_id)`;UQ `(scope_id, rag_id, namespace, external_key_hash)` | `rag_id`、完整 `external_key`、`state`(active/deleted)、`target_source_type/id`、`target_content_generation`、`target_config_revision`、`last_change_seq`、`version`、`deleted_at`;身份预留与成员关系 | -| `pc_document_nodes`/document | PK `(scope_id, document_id, revision, node_id)` | `kind`(section/block)、`parent_node_id`、`ordinal`、`title/text`、`source_locators`、`parser_metadata`;不可变原始解析证据与层次 | -| `pc_document_chunks`/document | PK `(scope_id, document_id, revision, chunk_id)`;UQ `(scope_id, document_id, revision, ordinal)` | `section_id`、`text`、`content_digest`、`source_locators`、`origin`、`base_revision`、`edit_source_type/id`、`metadata`;完整有效内容快照 | -| `pc_rag_index_generations`/rag | PK `(scope_id, rag_id, generation_id)` | `state`(building/ready/active/retired/failed)、`config_revision`、不可变 `profile_snapshot`、`start_seq`、`applied_seq`、`cutover_seq`、`build_fence`、`error`;独立配置构建 | -| `pc_rag_document_publications`/rag | PK `(scope_id, rag_id, generation_id, document_id)` | `document_revision`、`target_content_generation`、`chunk_count`、`index_digest`、`version`;选择索引完整的内容,不代表成员或 head | -| `pc_rag_jobs`/应用服务 | PK `(scope_id, job_id)`;UQ `(scope_id, request_scope_key, operation, idempotency_key)` | 按操作填写 `rag_id/document_id`、`binding_name`、`parent_job_id`、精确 Source、`request_digest`、`profile_snapshot`、`target_content_generation`、`generation_id`、`change_seq`、`stage/state`、`attempt`、`lease_token/expires_at`、`next_attempt_at`、`receipt`、脱敏 `error`、`actor`;回执、逐项任务和索引变更工作 | -| `pc_source_lifecycle`/共享 Source 服务 | PK `(scope_id, source_type, source_id)` | `state`(active/deleted)、`delete_generation`、`deleted_at`、`deleted_by`、`reason`、`delete_operation_id`;首期用于文档输入及其编辑 Source | -| `pc_rag_chunk_index`/rag 后端适配 | PK `entry_id`;UQ `(scope_id, rag_id, generation_id, document_id, revision, chunk_id)` | 完整目标键、`searchable_text`、`embedding_input_digest`、`vector_space_id`、`embedding`、`source_digest`;精确 chunk 的派生索引条目 | - -request_scope_key 是服务端生成的非空规范键:建库使用 Scope+操作,库内命令使用目标 rag,删除 Source 使用精确 Source 身份。 -内部任务使用确定性键,不能因为 rag_id 可空而破坏幂等唯一性。请求摘要覆盖操作、目标、规范化输入描述和前置条件。 -接受后的快照固定,即使原路径内容变化,重试也返回原回执;新文件版本必须使用新请求键。 - -完整 external_key 与定长身份 hash 一起保存;碰撞时比较完整值,不能静默合并。接受导入时预留 document ID 和归属行,内容处理成功后 -才创建 Artifact,因此预留行不能提前要求 document head 外键存在。内容/node/chunk 引用必须定位到 -`(scope, family=document, document_id, revision)`,rag 引用定位到 family=rag。同库关联使用组合约束或事务校验。公开删除不执行 SQL 级联。 - -manifest 包含 root SourceRef、parser/OCR/chunker 快照标识、chunk_count、chunks_digest 和 schema 版本。 -章节/block 父子引用只能位于同一 revision,且不能成环;chunk 定位关联这些 blocks,在发布前校验 ID 和顺序。 -编辑 Source payload 提供审计信息,不新增审计主表。 - -### 3.3. 索引与后端映射 - -| 访问路径 | 必要索引/约束 | -| --- | --- | -| 列出库内文档 | 成员表 `(scope_id, rag_id, state, document_id)`,不扫描 Scope 全部 Artifact | -| 读取 revision chunks | 唯一 ordinal 索引;keyset 游标固定 revision 和最后 ordinal/chunk ID | -| 查 Source 依赖 | lineage 反向索引;每次编辑继续保留 root 依赖 | -| 领取任务/恢复租约 | `(binding_name, state, next_attempt_at, job_id)` 和 `(state, lease_expires_at)` | -| 追平重建 | 持久变更任务 `(scope_id, rag_id, change_seq)`;构建仍需使用的回执不得丢弃 | -| 检索发布内容 | generation/publication 键与 chunk 索引 UQ;排名前约束精确 revision | - -SQLite 使用 FTS5 和稳定的 entry/row-ID 映射,向量使用经过验证的 sqlite-vec 适配或其他明确支持的精确实现。 -缺少向量能力不能静默降级混搜。SeekDB 和 OceanBase 分别验证全文/向量适配。embedding 为逻辑列,实际可能按维度分表或使用 -不同向量结构,但都映射到精确 chunk 键。核实后端索引长度限制,不能截断身份。模型/profile 变化创建新 generation,不覆盖旧向量。 +| `pc_document_imports` | PK `(scope_id, document_id)`;UQ `(scope_id, rag_id, collection_id, path_hash)` | 完整相对路径、binding name、当前/目标 SourceRef 与摘要、处理/配置快照和指纹、目标代次、operation(import/reprocess/edit)、有界待处理编辑、request ID/digest、state/stage、attempt、重试时间、lease token/expiry、结果 revision 和 error;合并身份预留、成员关系和逐文件最新工作 | +| `pc_document_chunks` | PK `(scope_id, document_id, revision, chunk_id)`;UQ `(scope_id, document_id, revision, ordinal)` | text、内容摘要、标题路径、续块/重叠元数据、规范化跨度和原文字节/图片定位、origin、编辑/base 引用;完整不可变 revision 快照 | +| `pc_document_source_states` | PK `(scope_id, source_type, source_id)` | 不可变 owner rag_id、document/文件身份、state=active/deleted、删除代次/时间;原始 Source 及其系统编辑 Source 的独立可变生命周期 | -人工编辑事务写入系统 Source、新 manifest、完整 nodes/chunks 快照、lineage、目标代次和索引任务,保留成员关系。 -索引 Worker 构建不可见条目、核验覆盖与摘要后,通过 CAS 切换 publication 行。全库重建捕获 change_seq 并追平到切换水位; -新增、更新、移除和目标变化均在所属事务中递增序号。Source 删除另用 Scope 可见代次校验,不等待逐库传播完成。 +解析前预留 document ID,但不要求 Artifact head 已存在。提交后明细引用同 Scope 的 family=document,每个 Source owner +匹配预留记录和不可变 payload。Manifest 保存所属 rag、root SourceRef、schema/处理指纹、chunk 数量/摘要和人工修改标记。 +100 块的 revision 保存一条 manifest 和 100 行明细;移除一块生成新 manifest 和 99 行,不改原来的 100 行。 +未变行可高效复制,但不完整快照不能可见。历史版本按精确引用读取,不能用当前 head 解释历史。 -取消/过期构建不能变为可见。首期保留已删除记录和索引,因此存储会随版本和重建增长,需要暴露保留量/可见量及容量不足错误。 -恢复、垃圾回收和永久擦除后续单独设计,不是 DELETE 的隐含副作用。 +按 `(scope, rag, document_id)` 索引导入记录,按 binding/状态/重试时间查待办,按 revision/ordinal 读 chunks, +按 `(scope, rag, document_id)` 索引 Source 状态支持删除传播。核实既有反向 lineage 查询路径以支持原始 Source 撤销。 +Hash 键同时保留完整原始身份用于比较。Source 行归属不随状态/进度改变。 +导入表保留最新目标和结果,不记录无界批次或命令历史。Source 接受前的错误归采集诊断;完整持久批次历史需另行明确扩展范围, +不能用元数据行里的无界 JSON 数组实现。 -## 4. 定向异步任务与发布 +## 5. 复用 Worker,内容与索引原子提交 -导入请求固定 Scope、目标 rag、精确 SourceRef、逻辑文档身份、处理配置快照和输入/请求代次。接受或复用 Source 与记录目标工作 -必须原子完成。仅依赖 Source journal 重放不够:已有 Source 导入另一 rag、重试和配置重建可能不新增 Source,必须显式请求处理。 +应用服务协调三个插件,不是新增插件或服务。Source 接受/复用、生命周期初始化、document 目标预留/更新和 +processing_intents.request() 同事务提交,唤醒通知丢失后也能从持久目标恢复。 +仅提交 Source 的入口也必须调用同一接受能力,不能绕过目标验证。 -复用 Scope/binding 的监督、租约、超时和执行栅栏。Worker 领取持久目标工作,不向所有 rag 广播 Scope 中的每个 Source。 -阶段包括解析/OCR、切块与内容提交、索引构建、发布。工作项遵循以下状态转换,并使用有上限的重试策略: +Supervisor 保持 Scope/binding 调度,document processor 选择导入表中的待办,不向所有 rag 广播 Source。 +已有 Source 的重试/重处理使用显式请求,不伪造正 source_through,也不为纯目标工作推进 Source cursor。 ```text -queued -> running -> succeeded - +--> retry_wait -> queued - +--> failed -queued / running / retry_wait -> cancelled 或 superseded -failed -> 经授权的显式重试 -> queued +pending -> running -> succeeded + +--> retry_wait -> pending + +--> failed / blocked +新目标 -> 目标代次递增,旧执行结果过期 +rag/document/Source 删除 -> 受影响目标 cancelled,禁止后续提交 ``` -暴露阶段、失败原因、attempt,以及最新内容和可检索 revision。首次失败时可以尚无 document Artifact。重试失败的持久阶段, -不重复生成内容版本或发布。同一幂等键携带不同请求摘要时返回冲突。 +每个逻辑文档只处理一个当前目标。相同待办合并,新的文件版本可以取代旧解析;人工编辑要求不存在冲突的待处理变更。 +持久保存操作、固定输入/配置、base revision 和最新请求 token,使重启后能重试相同工作。 +当前 token/digest 重放返回当前状态,同 token 不同内容冲突;过期 token 版本不能重新创建工作,不承诺无限期的历史回执重放。 -| 边界 | 原子记录/必要校验 | +| 边界 | 工作 | | --- | --- | -| 快照准备 | 接受前保存字节;失败后的无引用快照保留,待后续 GC 策略处理 | -| 导入接受 | Source 接受/复用、已验证的目标请求和持久调度意图 | -| 内容提交 | 完整 manifest/明细、溯源、已验证的成员关系、内容回执和索引工作;人工编辑在此创建系统 Source | -| 索引发布 | 校验完整索引、精确内容目标、生效配置、执行资格和生命周期;切换可检索选择及可见代次 | -| 软删除 | 确认前持久化所属生命周期标记、推进可见代次并保存幂等回执;不物理清理 | +| 事务外 | OpenDAL 快照采集、解析/OCR、Markdown/chunk 构造、embedding 和索引投影准备 | +| 接受事务 | 校验归属/生命周期和前置条件,接受/复用 Source 与目标状态,提交现有 processing intent | +| 内容事务 | 重验目标代次、base head、所属 rag/Source 生命周期、插件 profile/build 和 Worker 栅栏;一起提交 manifest、完整 chunks、lineage、必要系统编辑 Source、head、索引和目标成功状态 | +| 删除事务 | retire 父 Artifact 或标记 Source 已删,使目标失效;利用现有 invocation 和目标行持久化可恢复的传播工作 | -OCR、embedding、DDL 和批量索引构建都在上述短事务外执行。每次提交重新校验注册/租约栅栏、目标状态及输入/配置/删除代次。 -新的编辑或导入使旧发布任务失效。持久工作记录是恢复依据,进程内通知仅加速唤醒。 +模型调用和 DDL 不在内容事务里执行。Chunk 投影适配器从完整 chunk 快照准备索引,不能假设有界 manifest 包含全文。 +提交时同时校验快照和投影指纹,现有通用 JSON 字段投影不经适配并不满足要求。 -内容 head 与可检索 revision 分离。索引失败时保留旧发布版本,同时展示新内容和错误。rag 重建使用新 generation,在切换前追平已接受 -变更到经验证的水位,不能用部分构建替换当前 generation。重建一个知识库不得切换其他库的 generation。文件系统/数据库备份恢复后, -应验证被引用快照和索引一致性,再开放恢复后的检索。 +正常更新失败保留原提交 head 和索引,不生成“已可读但尚未索引”的新 revision。历史内容可精确读取,检索使用当前索引 revision。 +共享 document family 索引重建或不可用时,延后新文档提交并明确报告不可用;不能静默走通用框架“重建时仅提交内容”的路径, +不能回退 Memory 检索,也不承诺无停机切换。重建读取已提交 chunks,不重新 OCR。 +SQLite、SeekDB、OceanBase 都需通过真实适配验证事务/读取;原生 ANN 无法保证过滤语义时,使用限定集合精确检索或明确报能力不足。 -现有 `pc_artifact_processing_pending.source_through` 要求正 Source 水位。纯目标任务通过 requested intent 代次和持久任务调度, -不得伪造 Source 水位或推进 Source cursor。领取任务固定自身 lease token 和 Supervisor/binding 栅栏,每次 checkpoint 都比较。 -租约过期允许恢复,不允许旧 Worker 继续提交。 +## 6. 编辑、chunk 移除与软删除 -## 5. 人工编辑、重处理与删除 +编辑命令支持已有 chunk 的 replace_text 和 remove,使用 document If-Match。Worker 构造完整新 revision,重新校验数量/顺序/摘要, +准备索引后原子提交。允许删除最后一块:有效内容为空、索引片段数为零,但保留可读 manifest 和溯源。 +未变 chunks 保留逻辑 ID,重切块生成新 ID;引用始终带 revision。Remove 只影响新快照,不物理删除历史 chunk 行。 -首期只允许替换一个已有 chunk 的文字,以 document head ETag 做并发控制;不开放 chunk 增删、合并或重排。超长编辑明确拒绝, -不静默重切块。编辑一个 chunk 不自动修改其他 chunk 中的重叠文字。 +成功提交时创建 role=lineage_only、operation=artifact_replace 的系统 Content Source,记录精确新 revision、base revision 和编辑/移除命令。 +该 Source 用于修改溯源,不进入普通解析。显式保留原始文档 Source 依赖,不能假设通用替换已自动继承。 +修改文字标记 origin=manual_edit、verbatim=false,原图位置只是修改依据,不表示新文字逐字存在于图片。 +移除 chunk 也算人工修改,重解析不能静默覆盖。完整实际 embedding 输入/profile 未变时可复用计算,但仍更新新 revision 的索引映射。 -沿用 Artifact 管理的溯源模式:在内容事务中创建 `role=lineage_only`、`operation=artifact_replace` 的系统 Content Source, -再提交新 document revision 和索引工作。记录 base revision、修改内容、操作者/原因及精确目标。该 Source 不再次进入解析。 -除编辑 Source 和 base revision 外,显式保留原始输入 Source 依赖,不能假设通用替换溯源会自动保留根输入。 - -人工替换保留逻辑 chunk ID,但引用始终包含 revision。重新解析/切块生成新 chunk ID,序号不代表身份。编辑后的结果标记 -`origin=manual_edit` 和 `verbatim=false`;原始定位是修改依据,不表示修改后的文字逐字出现在原文中。 - -更新同步全文条目、向量映射、发布选择及受可见性约束的缓存。只有完整实际输入和模型/profile 身份一致时才可复用 embedding 计算, -即使复用也必须索引新 revision 地址。仅修改 embedding/索引配置保留人工编辑内容。重处理含人工修改的内容必须显式指定 -`manual_edits_policy=discard`,否则冲突。Source 替换/重解析尚未提交时拒绝编辑;已提交内容仍在索引时允许继续编辑,并使旧索引 -任务失效。这些条件必须和目标状态一起原子校验。 - -**首期仅实现软删除。** Source payload、原文快照、document revision、chunks、编辑证据和索引均保留,不提供恢复或永久擦除接口。 -删除表示不能再通过受支持的应用接口获取内容,不代表数据库备份或管理员存储访问中的数据被擦除。保留 tombstone,防止身份复用和意外恢复。 - -| 删除对象 | 权威标记 | 立即生效范围与保留对象 | -| --- | --- | --- | -| 文档 Source | `pc_source_lifecycle.state=deleted` 与 Scope 可见代次 | 所有依赖它的 revision 不可用,包括同 Scope 多个 rag 内的人工编辑版本;rag 配置保留 | -| document | `pc_rag_documents.state=deleted` 与 rag 可见/变更计数 | 其全部 revision/chunks 在成员读取、通用读取和检索中不可用;Source 和其他文档保留 | -| rag | `pc_rag_runtime.state=deleted` 与 rag 可见代次 | 知识库及内部文档不可用;Scope、共享 Source 和其他 rag 保留 | - -可见性是多个条件的交集,不需要给每行复制一个删除布尔值:普通内容读取要求 rag 未删除且启用、document 成员有效、根 Source 未删除。 -检索额外检查 active generation 和精确发布 revision。历史读取可指定旧 revision,但仍检查其所属对象和 Source 状态。 -根输入必须取自被读取的 revision,不能使用成员表中最新 target Source。历史 base revision 链接不代表传递性的内容依赖; -完整重解析的替代版本声明自己的根输入。 -停用 rag 的配置/状态仍可供有权限的用户管理,内容检索关闭;重新启用停用 rag 不等于恢复已删除 rag。 - -删除 Source 不必同步更新每个 chunk/成员行,根标记和可见代次即可立即拒绝读取。管理状态根据这些标记计算实际不可用原因。 -携带派生正文的系统编辑 Source 也必须通过精确 document 目标和不可变 root Source 引用校验,普通 Source、通用 Artifact、历史、 -chunk、原图和缓存读取均不能绕过。 -原始 Source 具有独立的 Scope/生命周期授权,单独删除 rag 或 document 不撤销该 Source 及其原文件直读。 -编辑 Source 保存的是派生文字,必须检查 document/rag 目标。公开 Source DELETE 仅针对原始文档输入,编辑 Source 由系统管理。 - -保留 lineage 外键及 RESTRICT 约束,公开 DELETE 不物理删除 Source/Artifact 行。重复删除返回原回执,不再次推进代次。 -向已删除身份导入返回 410;必须显式选择新身份。首期没有清除删除标记的操作。在途读取返回前重新校验,迟到任务不能提交或发布。 +| 删除操作 | 状态与影响 | +| --- | --- | +| Source | sidecar 标记 deleted,不改 payload;当前输入仍为它的 document retire,相关历史 revision 和编辑 Source 不可读;仅依赖替代 Source 的当前版本保留 | +| Document | Artifact head retire,阻断全部 revision/chunks 和待办;不删除原始 Source | +| rag | head retire,立即阻断全部所属内容,再持久完成所属全部 Source 版本和 document head 的删除/retire 标记,包括尚未处理成功的目标 | +| Chunk | 生成不包含该块的新 document revision,保留历史内容 | + +Retire 复用 lifecycle_state=retired 和 governance CAS,不新增第二套 rag/document 删除标记。 +Source payload 不可变,因此删除放在 sidecar。重复删除幂等。 +仅预留、尚无 head 的 document 在导入行以 document_deleted 原因终止,不为删除而创建空 Artifact;后续扫描不能静默恢复该身份。 +删除待处理替代 Source 只取消其目标,不 retire 依赖另一 Source 的已提交版本。 +较大级联可分批完成:已 retire rag 和持久归属使未完成工作可重新发现,父状态立即阻断读取/提交。 +Source 不跨 rag 共享逻辑归属,因此删库不误删其他库的 Source。保留 OpenDAL 快照和 canonical/历史内容,不删除用户原文件; +首期不提供恢复或永久擦除。 + +检索及通用精确/历史/chunk 读取校验所属 rag、document head 和该 revision 的根 Source。 +历史 base revision 链接不让完整重解析的替代版本传递依赖旧 Source。系统编辑 Source 也检查其 document/rag 目标。 +原始 Source 读取检查自身状态和 owner rag;单删 document 后原始 Source 仍可读,删其 rag 后不可读。 +必须增加 family 读取校验,不能只依赖通用 retirement,因为既有行为可能仍允许精确读取。 + +搜索索引是派生结构,不是历史证据,沿用现有替换/移除/重建维护。软删除保留业务数据,不承诺原样保留每个历史索引条目。 +即使旧索引暂存,排名前也必须排除,包括删除传播恢复期间。不论物理索引是否清理,都必须检查父对象/Source 和提交栅栏。 已经发送的响应无法收回。 -删除旧 Source 不影响仅依赖替代 Source 的 revision。若当前发布的旧 revision 依赖已删 Source,即使替代版本仍在索引,也必须立即不可用。 -不能用旧版兜底、静默发布未完成索引的替代版本,或让人工编辑内容跳过 Source 校验。 - -## 6. 检索与公开接口 - -查询显式选择完整 rag 引用,可位于同一 Scope 或多个已授权 Scope。不能仅凭 Scope 默认选第一个或全部知识库。 -逐目标授权,在全文/向量通道内落实成员、元数据、生命周期、已发布 revision 和 generation 过滤,不能先取整个 Scope 的 top-k 再过滤。 -后端 ANN 无法满足合格候选集合过滤时,使用经过验证的过滤集合内精确向量检索,不静默改变检索契约。 +## 7. 统一接口契约 -限制候选数量并采用确定性的排名融合。不同 embedding profile 使用兼容的查询向量,不能跨库比较不兼容的原始分数。 -去重保留不同来源证据。结果返回正文、Scope/rag、document/revision/chunk、SourceRef、定位、编辑标记及实际索引 profile/generation。 -逐目标失败与无命中分开报告,全部目标失败时返回失败。Parser、chunker、检索策略和可选 rerank 扩展均须保持预算与证据契约。 +以下路由为建议复用或扩展,当前 schema 尚未支持全部 family/filter。实现时修改 openapi/powercontext.yaml 并重新生成绑定。 +复用权限、错误封装、Artifact/Source 引用、分页、ETag 和 SDK/MCP 映射。 +不把文档文件塞进目前只接受 built-in content 的通用 create-Source 命令,使用 Source 插件协议。 -复用通用 Artifact 创建/读取/替换/revision/tag 的形状、完整引用、分页、错误和条件写入约定,新增定向导入、任务查看/重试、 -固定 revision 的 chunk 读取、chunk 编辑、检索和 Source 撤销等领域能力。不开放能绕过溯源和归属校验的任意 document 替换。 -HTTP、Python client 和必要 MCP 能力保持一致,知识库上下文显式选择,现有 Memory 检索默认行为不变。 +约定 `R=/v1/scopes/{s}/artifacts/rag/{r}`,`D=/v1/scopes/{s}/artifacts/document/{d}`。 -下述路由和 payload 是建议契约,实现时写入 `openapi/powercontext.yaml`,生成客户端并运行契约检查,不表示接口已经可用。新 family 和明细表通过三个后端的版本化迁移引入;既有 Source 和 Artifact family 保持原契约,不自动转换或加入文档处理。 - -### 6.1. 接口清单 - -约定 `R = /v1/scopes/{scope_id}/artifacts/rag/{rag_id}`, -`D = /v1/scopes/{scope_id}/artifacts/document/{document_id}`。以下路由尚未发布。 -复用现有 ArtifactReference、ArtifactAddress、SourceTypeReference、ETag、Location、分页、ErrorResponse 和 Scope 权限, -不另建通用 Artifact CRUD 协议。 - -| 操作 | 路由/契约 | 权限/返回 | +| 操作 | 复用或必要扩展 | 语义 | | --- | --- | --- | -| 创建 rag | 复用 POST `/v1/scopes/{s}/artifacts`,family=rag 与类型化 content;为此命令扩展可选 idempotency_key | scope.contribute;201 ArtifactCreated、ETag、Location | -| 列出/读取/配置 | 复用 family list、GET/PUT `R`、revisions/tags;配置 PUT 携带当前 Artifact If-Match,完整替换 content | 读 scope.read,配置 scope.contribute;200、ETag | -| 运行状态 | 新增 GET/PUT `R/runtime`;PUT 接受 enabled 和 expected_version,不生成配置 revision | 读 scope.read,控制 scope.admin;200 运行版本/状态 | -| 批量导入 | 新增 POST `R/imports`;idempotency_key、items,每项有唯一 item_key、namespace/key 和输入描述 | scope.contribute;202 父任务和逐项回执 | -| 浏览成员 | 新增 GET `R/documents`;cursor/state 过滤,包含预留目标、成员版本、实际可用状态及内容/发布版本 | scope.read;200 items/next_cursor | -| 文档/历史 | 复用 GET `D` 和 revisions;manifest/溯源均检查生命周期 | scope.read;200、ETag | -| Chunk/证据明细 | 新增 GET `D/revisions/{rev}/chunks` 和 `/nodes`;分别返回有效 chunks、原始证据,支持 cursor/limit | scope.read;200 items/next_cursor,固定 revision/view | -| 编辑 chunk | 新增 PATCH `D/chunks/{chunk_id}`;document If-Match、text/reason/idempotency_key | scope.contribute;202 新 revision 和索引任务 | -| 重处理 document | 新增 POST `D/reprocess`;document If-Match、幂等键,必要时显式 manual_edits_policy=discard | scope.contribute;202 任务 | -| 重建 rag | 新增 POST `R/rebuilds`;config_revision、mode=index_only/reprocess、幂等键和必要的编辑丢弃策略 | scope.admin;202 generation/任务 | -| 查看/重试任务 | 新增 GET `/v1/scopes/{s}/rag-jobs/{job_id}`,POST `.../{job_id}/retry` 使用新幂等键,保留原接受目标/输入 | 读 scope.read,重试 scope.contribute;200 状态/202 回执 | -| 多库检索 | 新增 POST `/v1/rag/query`;显式 targets、query、top_k、类型化 filters 和有界选项 | 每个目标 scope.read;200 命中和逐目标结果 | -| 原始输入 | 现有 Source GET 返回描述;新增 GET `/v1/scopes/{s}/sources/{type}/{id}/content` 返回快照流 | scope.read;200、媒体类型,不暴露存储凭据 | -| 软删除 document | 新增 DELETE `R/documents/{document_id}`,expected_version 取成员版本 | scope.contribute;200 回执 | -| 软删除 rag | 新增 DELETE `R`,expected_version 取运行状态版本 | scope.admin;200 回执 | -| 软删除 Source | 新增 DELETE `/v1/scopes/{s}/sources/{type}/{id}`,首期仅适用文档 Source 生命周期 | scope.admin;200 回执 | - -DELETE 携带 Idempotency-Key,要求 expected_version 的操作将其作为查询参数。回执包含 operation_id、目标、state=deleted、 -deleted_at 和 data_retained=true,不隐含清理任务。重复 DELETE 返回原回执。管理任务可报告删除状态,但不返回保留的正文; -普通内容 GET 在授权后返回 410,不提供 include_deleted 内容绕过选项。 - -创建空 rag 时原子创建初始运行/generation 元数据,不调度解析。配置 PUT 保存目标配置,导入使用生效配置,配置变化不静默重解析人工编辑。 -显式 rebuild 在校验切换后激活目标快照,index_only 拒绝 parser/OCR/chunker 变化。重建期间的导入/编辑持久保存,切换前追平。 -分别展示目标和生效 revision;重建失败保留旧生效配置与索引。 -普通文档更新期间,有效发布 revision 无须等于最新 head 或目标代次,这是索引期间的预期差异;成功发布后才切换。 -生命周期撤销始终优先于旧版可用的兜底规则。 - -文件输入使用已授权 Source binding 加相对路径,或同 Scope 精确 SourceTypeReference。客户端任意填写的服务器路径、URL 或快照位置 -不构成访问授权。插件负责捕获字节和校验媒体/摘要,复用 Source 也须调度目标工作。接受前校验权限和批次形状;逐项采集失败可以与 -成功项共存,但每个接受项必须原子保存 Source、身份预留、任务和 intent,明确报告部分接受。批次重试返回原逐项回执; -没有固定输入的采集失败使用新键重新提交,Worker 重试则继续使用已接受快照。 - -### 6.2. 典型请求与响应 - -**创建**沿用 family + content。以下 profile 是示例部署 binding,不是硬编码默认值。rag content schema 拒绝未知字段,不保存密钥或成员数组。 +| 创建/配置 rag | 现有 POST `/v1/scopes/{s}/artifacts`、GET/PUT `R`、revisions/tags | family=rag,完整配置替换和既有 If-Match;创建空库不解析 | +| 导入目录/文件 | 现有 POST `/v1/source-management/add`,使用发现的 collect capability 和 instance | 插件 input 携带 owner rag 和本地根目录/文件;Source 回执仍表示采集,不新建 rag import/job 封装 | +| 采集状态/控制 | 现有 source-management status 和 target/instance controls | 不声称 collect add 会重新调度 stopped target,也不把 status 当完整批次历史 | +| Source/document | 现有 Source list/get、Artifact list/get/history | 缺少时增加经过验证的 owner-rag 过滤;document GET 返回有界 manifest,不返回所有 chunks | +| 最新逐文件进度 | 新增 GET `R/processing`,cursor/state 过滤 | 最新目标、阶段、attempt/error、请求代次和已提交 revision,包含无 Artifact 的预留记录 | +| 重试/重处理 | 新增 POST `D/processing`,首次失败无 head 时也可使用预留 document ID | action、expected_target_generation、request_id、可选丢弃策略;202 当前目标回执 | +| 读取 chunks | 新增 GET `D/revisions/{rev}/chunks` | 复用 items/next_cursor,精确 revision 的有效 chunks 和出处 | +| 编辑/移除 chunk | 新增 POST `D/edits` | document If-Match、有界类型化操作和 request_id;202 仅表示待办,原子成功后才生成新 revision | +| 检索 | 现有 POST `/v1/scopes/{s}/artifacts/document/search` | 沿用 query/mode/limit/fusion,要求经过验证的 filters.rag_ids;可选匹配片段不替代完整 Artifact 结果 | +| 软删除 Artifact/Source | 给现有精确 Artifact/Source 资源路径增加 DELETE | family writer/Source 生命周期服务校验归属;Artifact 使用 expected_generation(治理 CAS);document 为 scope.contribute,rag/Source 为 scope.admin | + +rag content 保存标题/摘要和 parser/OCR/chunker 配置或引用,不保存运行进度、成员或主路径 embedding 配置。 +修改配置影响后续接受的目标;已有 document 通过显式重处理更新,并继续保护人工修改。 + +创建示例,沿用通用 Artifact 封装: ```json -{ - "family": "rag", - "idempotency_key": "create-ops-01", - "content": { - "schema_version": "1", - "title": "Operations SOPs", - "summary": "Runbooks and screenshots", - "profiles": { - "parser": "markdown-v1", - "ocr": "rapidocr-local-v1", - "chunker": "heading-paragraph-v1", - "embedding": "docs-embedding-v1", - "retrieval": "hybrid-v1" - } - } -} +{"family":"rag","content":{"title":"Operations SOPs","summary":"Runbooks and screenshots","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} ``` -**导入**已有 rag,每项只选择一种输入形式: +目录采集示例,capability/instance 名称和参数是部署发现值的示意: ```json -{ - "idempotency_key": "import-ops-01", - "items": [ - {"item_key": "a", "namespace": "oceanbase-docs", "external_key": "README.md", - "input": {"kind": "file", "binding_name": "local-documents", "path": "README.md"}}, - {"item_key": "b", "namespace": "ops-images", "external_key": "restart.png", - "input": {"kind": "source", "source": {"source_type": "knowledge-document-input", "source_id": "image-42"}}} - ] -} +{"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} ``` -202 响应包含稳定父任务、逐项 Source 引用和预留 document ID;内容尚未生成时 document=null。父任务计数区分接受和成功。 -逐项回执暴露 stage=accepted/parse/chunk/index/publish、state、attempt、最新内容/可检索 revision 和 error。 -父任务聚合可报告 partial_failure,不把它加入单项工作状态机。 +接受时验证目标 rag 引用;归属固定为 rag ID,处理固定已接受配置。scan_token 不是文档身份,不改变 Source 协议顶层 schema。 +客户端重试扫描沿用 token,明确再次扫描使用新 token。 -**编辑**使用 PATCH `D/chunks/chunk-3`,If-Match 为 document GET 返回的 ETag: +移除 chunk 示例,POST `D/edits` 携带当前 document ETag: ```json -{"idempotency_key": "edit-03", "text": "Restart the follower before the leader.", "reason": "Correct OCR text"} +{"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} ``` ```json -{ - "document": {"family": "document", "artifact_id": "doc-1", "revision": 2}, - "index_job_id": "job-12", - "latest_content_revision": 2, - "searchable_revision": 1, - "chunk": {"chunk_id": "chunk-3", "origin": "manual_edit", "verbatim": false} -} +{"document_id":"doc-1","request_id":"edit-03","target_generation":4,"state":"pending","committed_revision":2} ``` -**检索**的每个 rag 复用 ArtifactAddress。目标 revision 固定调用者所见的配置 head,过期时返回冲突。 -响应单独标明生效索引/配置,它可能落后于目标配置。 +回执不能提前虚构 revision 3。稍后 GET processing 返回成功和新提交版本,或失败且 revision 2 不变。 +文字替换使用 kind=replace_text 并提供 text,不把局部操作伪装成通用 PUT 的完整 content。 +当前 request ID/digest 重放复用目标,冲突或过期请求返回冲突/前置条件错误,不静默再次执行。 + +同 Scope 检索沿用通用请求: ```json -{ - "targets": [ - {"scope_id": "project-p", "artifact": {"family": "rag", "artifact_id": "ops", "revision": 1}}, - {"scope_id": "project-q", "artifact": {"family": "rag", "artifact_id": "product", "revision": 3}} - ], - "query": "How should I restart a follower?", - "top_k": 10, - "filters": {"media_types": ["text/markdown", "image/png"]}, - "retrieval": {"mode": "hybrid", "candidate_limit": 100} -} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} ``` -每条命中包含 Scope、rag/document ArtifactReference、chunk ID/text/rank/score、SourceTypeReference、支持的定位、 -origin/verbatim 和索引 generation。响应返回逐目标状态/错误及 partial。权限失败在检索前拒绝整个请求;已授权目标的运行失败 -可返回明确部分结果,全部目标失败仍是错误。 +results 继续返回完整 document Artifact manifest 和 lineage。在搜索项上增加可选类型化 matches,携带有界精确 chunk 命中: +chunk ID、text、locator、origin/verbatim 和片段得分。这是响应投影,不写入 Artifact content。 +limit 仍限制返回 Artifact 数量,每 document 的片段数量另有能力上限。只接受已声明 document filters/options, +不支持的 rerank 明确报能力错误;未知 filter 或未指定 rag 均不能扩大查询范围。 -### 6.3. 错误、并发与能力启用 +跨 Scope 查询由客户端/helper 接受明确的 `(scope, rag)` 目标,先逐个授权,再分组调用同一个现有搜索操作并按排名融合。 +保留 document/chunk 身份和逐目标错误,不比较不兼容原始分数,不把失败当无命中。 +首期不新增独立 /rag/query 协议;HTTP、Python、MCP 使用同一 family 操作,必要时执行有界编排。 -| 情况 | 契约 | +| 情况 | 响应 | | --- | --- | -| 相同键/摘要 | 校验当前授权/生命周期后重放稳定回执;删除重放其 tombstone 回执 | -| 同键不同摘要 | 409 idempotency_conflict,不创建新工作 | -| 缺失/过期内容或配置 ETag | 复用 428/412 前置条件响应 | -| 过期运行/成员版本、rag 配置或正在重解析 | 409 和机器可读原因,不部分提交 | -| 目标/证据已删除 | 授权后 410 resource_deleted,错误不包含正文 | -| 不支持输入、非法配置、过长编辑 | 422;接受前传输字节限制可返回 413 | -| 缺少后端/模型能力 | 503,不当作无命中 | -| 已接受任务异步失败 | 任务 failed/retry_wait;202 不表示处理完成 | +| 缺少/过期 document/配置 ETag | 既有 428/412 前置条件错误 | +| 目标代次/请求冲突、存在待处理编辑或缺少人工修改丢弃策略 | 409 与可操作错误码 | +| 对象或证据已删除 | 授权后 410,错误中不返回保留正文 | +| 格式/配置非法或输入超限 | 422;传输层可用 413 拒绝大请求 | +| 索引/模型不可用或重建中 | 503,不静默降级纯全文或检索其他 family | +| 已接受处理失败 | 最新目标 failed/blocked/retry_wait,Source 接受和处理成功分开 | -沿用现有错误封装: +错误继续使用现有结构,例如: ```json -{"error": {"code": "resource_deleted", "message": "The requested document is unavailable.", "details": null}} +{"error":{"code":"resource_deleted","message":"The requested document is unavailable.","details":null}} ``` -内容写入比较 document head,索引写入比较精确目标/publication 版本,都原子更新状态和持久工作。 -重放查询先于旧写入前置条件的再次检查,但不能绕过当前权限/删除。失败命令回滚回执和业务写入,暂存内容完整前不可见, -重放响应也不能泄露随后被删除目标的文字。 +## 8. 实现与验收 -迁移先创建 schema/索引/能力声明,再启用功能。新文档 Source 在接受时创建生命周期行,缺少必要生命周期/归属是完整性错误, -不能默认允许读取。无关 family 不变;缺少要求的后端/profile 能力时拒绝启用。通过公开 API 验证升级/重启、重复请求、 -写后读、发布竞态和删除过滤,不只直接写表验证。 +复用框架仍需文档 Source 接受 hook、Worker 逐文件选择、chunk 明细投影适配、top-k 前归属过滤、所有读取的生命周期校验,以及 +同事务 family writers。不能因为复用表而把全文塞回 manifest,或声称通用 JSON 投影已经足够。 +不计划修改核心元数据列;若实现发现真实缺口,加法领域迁移和 OpenAPI 扩展仍需评审。 -## 7. 验收与交付 +SQLite、SeekDB、OceanBase 各自通过公开操作验证: -使用 `oceanbase/oceanbase` 固定 commit 的 Markdown,以及文字/定位已核验的独立 OCR 图片。SQLite、SeekDB、OceanBase 均验证: +- 同 Scope 两个 rag 和另一 Scope 的 rag;同文件导入归属独占,查询不串库。 +- 固定 oceanbase/oceanbase commit 的 Markdown 和真实 OCR fixture,保留图片引用及准确出处。 +- 相同成功跳过、相同失败重试、字节变化生成版本、配置变化重处理、仅 embedding 变化不 OCR。 +- 迟到 Worker/冲突编辑拒绝,持久当前目标支持重启;内容或索引失败不暴露半发布版本。 +- 通过新 revision 移除 chunk,包括最后一块;旧快照完整,当前索引不命中已移除块。 +- Source/document/rag 软删除,重启后继续传播,历史/编辑 Source 读取校验,删除旧 Source 不误删替代版本。 +- 插件由兼容主路径配置初始化但不持续耦合,索引隔离,重建期间明确报告不可用。 +- 核心 schema 兼容、过滤混搜、分页和契约生成;mock 不代替真实后端/OCR 验收。 -- 同 Scope 多个空知识库、自动文档归属、精确引用、单库过滤,以及显式授权的同 Scope/跨 Scope 查询。 -- 已有 Source 复用、幂等重试、无 document 的首次失败、进程重启、内容/成员/工作原子提交,以及索引失败时旧版本可检索。 -- 真实 RapidOCR、非法/不支持输入和无文字结果、Markdown 图片引用保留,以及不扫描整篇 JSON 的 chunk 全文/向量检索。 -- 人工编辑溯源、完整快照、固定 revision 分页、全文/向量映射更新、重解析冲突、迟到 Worker 拒绝,以及并发更新下的 generation 切换。 -- Source/document/rag 软删除,历史/缓存/原文/编辑 Source 读取校验、物理数据保留、幂等删除,以及无关文档、替代 Source 版本和 rag 配置的保留。 - -沿用现有 Issue:#2441 负责基础与导入,#2442 负责处理/内容/索引生命周期,#2443 负责检索和接口,#2444 负责运行可见性与三后端验收。 -实现可采用一个集成分支和 PR,按这四个阶段评审。本 RFC PR 不完成这些实施 Issue。随实现发布支持格式、模型版本、资源限制和恢复说明, -不从功能样本推断生产容量。 +沿用 #2441 负责归属/导入,#2442 负责处理/内容/索引适配,#2443 负责检索/接口,#2444 负责诊断和三后端验收。 +一个实现分支/PR 可按这四个阶段评审。本 RFC PR 不关闭实施 Issue,不新增 Issue,也不从功能 fixture 推断大规模容量。 # 缺点 -完整快照使单块编辑也增加存储和写入成本。区分内容版本与检索版本增加读取和诊断复杂度。专用消费限制、定向任务、family writer 和 -撤销机制需要超出插件声明的框架适配。三后端增加迁移和索引测试成本,RapidOCR 模型分发及平台兼容性也需要明确维护。软删除保留全部数据和索引,不是擦除能力,需要监控存储容量。 +完整 chunk 快照增加存储与写入,软删除原文/历史保留需要容量监控。共享 document-family 重建可能影响同 Scope 多个 rag 的检索。 +逐文件最新状态比任务中心简单,但不提供完整批次/命令历史。即使核心 schema 不变,插件专用读取/投影/接受适配仍有实际开发量。 +OCR 分发和平台支持需测试。 # 设计理由与替代方案 -- **每个知识库一个 Scope:** 可以复用现有隔离,但会把集合组织绑定到授权和项目身份。多 rag 将这些职责分离,需要隔离时仍使用不同 Scope。 -- **将 chunks 存在可变 Source 中:** 混淆原始证据和派生内容,违反 Source 不可变原则。 -- **每个 chunk 一个 Artifact:** 将整篇文档更新拆成多个独立 Artifact 生命周期,难以表达原子文档版本。 -- **全部 chunks 放在 Artifact JSON 中:** 写入简单,但片段读取和索引依赖大 payload。 -- **独立知识库主表:** 重复已有 Artifact 身份、版本和管理设施。 -- **只靠 Source journal 生成:** 无法可靠表达空 rag 创建或已有 Source 复用引发的工作。 - -选定模型保留整篇文档身份,同时为 chunks 提供适合检索的物理存储和明确发布语义。不提供这一能力,会使各应用自行拼装不一致的导入、 -溯源和删除流程。 +- 一个知识库一个 Scope 会将集合组织绑定到授权;多个 rag Artifact 保留项目分组。 +- 跨 rag 共享逻辑 Source 会让删库影响其他库,仅在需要时共享物理快照字节。 +- 在 Source 存 chunks 破坏不可变证据,每 chunk 一个 Artifact 则难以表达整篇文档版本。 +- 全文 JSON 数组简化序列化,但会放大检索/明细读取。 +- 独立 rag runtime、发布代次和通用任务表可支撑更复杂能力,但内容/索引原子提交的首期无需这些结构。 +- 直接 SQL 删除 chunk 破坏旧 revision 数量、摘要和引用,用 revision 替换保留证据。 +- 运行时持续回退主路径 embedding 配置可能静默改变向量空间,插件持有解析后的配置可避免此问题。 # 既有设计 -本提案基于仓库的 [Source 插件设计](2012-source-plugin-system.md)、[Artifact 插件设计](2175-artifact-plugin-system.md)、 -[Source 模型](1400_source_definition_and_observation_model.md)、[Artifact 处理监督](1515_artifact_processing_supervisor.md)、 -[Source/Artifact API](1437_source_artifact_rest_api.md) 和 [Topic Memory](1417_topic_memory.md)。复用其扩展、溯源、调度和读取边界, -增加显式集合管理和文档专属存储/发布。Topic Memory 的专属明细/索引 schema 不作为共享文档 schema。 +基于 [Source 插件](2012-source-plugin-system.md)、[Artifact 插件](2175-artifact-plugin-system.md)、 +[Source 身份](1400_source_definition_and_observation_model.md)、[处理监督](1515_artifact_processing_supervisor.md) +和 [Source/Artifact API](1437_source_artifact_rest_api.md)。现有 OpenDAL 已比较路径/内容 hash,Artifact head 治理和通用片段索引 +提供复用基础,但并不表示知识库已经实现。Atomic Memory retirement 可参考,但不等于已有 Source 到 document 的级联契约。 # 待解决问题 -以下内容须在对应实现中固定并测试,不延后身份、原子性、消费限制和撤销语义: - -- 实现上述契约的 Python 能力/writer 签名、迁移 DDL 和后端索引布局。 -- 快照、解码图片像素、manifest、chunk、分页、Worker 并发、超时和重试限制。 -- 固定的 RapidOCR/ONNX/模型版本、支持的图片格式/平台,以及默认切块/embedding profiles。 -- 后续保留/擦除策略及过期引用响应;首期保留历史和软删除数据。 +实现需要固定能力签名、支持图片格式/模型版本、资源限制、后端迁移/事务行为,以及依据实际 embedding token 限制验证的默认参数。 +验证三表基线,不预先扩大。任何核心 schema 改动必须有真实缺口和评审依据。 -完整编辑文档导出需要明确重叠和编辑合并契约。独立 rag ACL、跨部署联合查询和共享 document 归属需要单独设计,不隐式提供。恢复和永久擦除还需明确依赖、授权与审计规则后才能开放。 +永久擦除、恢复、保留/GC、改名身份、完整批次历史、逐 rag 独立 embedding/重建和完整编辑 Markdown 导出需要另定契约。 +不能直接拼接重叠 chunks 声称得到准确的编辑全文。 # 后续可能性 -更多解析器、存储后端、自动采集、切块策略、rerank 和受限 agentic 检索可以复用组件边界。测量到实际存储压力后,可考虑跨 revision -共享不可变 chunk 正文。这些扩展必须保留精确证据、目标隔离、发布与删除语义,不作为首期知识库流程的前置条件。 +更多 OpenDAL provider、解析器、切块策略、rerank 和受限 agentic 检索可扩展组件边界。 +测量到实际存储压力后可考虑共享不可变 chunk 正文,这些都不是首期归属、去重、原子提交或精确证据的前置条件。 From ad8b16615ecb7e0c7720d000e8934263acb33039 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Tue, 10 Nov 2026 19:54:15 +0800 Subject: [PATCH 05/13] docs(rfc): reuse source journals for rag operations --- docs/en/rfcs/2570-rag-knowledge-base.md | 673 ++++++++++++------------ docs/zh/rfcs/2570-rag-knowledge-base.md | 530 ++++++++++--------- 2 files changed, 615 insertions(+), 588 deletions(-) diff --git a/docs/en/rfcs/2570-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md index 4fb746b473..4996308275 100644 --- a/docs/en/rfcs/2570-rag-knowledge-base.md +++ b/docs/en/rfcs/2570-rag-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570: Document knowledge bases with rag Artifacts" -description: "A proposal for OpenDAL document ingestion, simple Markdown chunking, plugin-owned retrieval, and versioned knowledge bases using existing Source and Artifact facilities." +description: "OpenDAL ingestion, versioned document chunks, and knowledge-base retrieval using Source journals, shared Workers, and Source lifecycle metadata." --- - Proposal Name: `rag_knowledge_base` @@ -11,43 +11,44 @@ description: "A proposal for OpenDAL document ingestion, simple Markdown chunkin # Summary -Provide knowledge bases through a document Source plugin and the `document` and `rag` Artifact families. A Scope -contains multiple user-created rags; each document Source and document belongs to exactly one rag. OpenDAL captures -local files, Markdown and image OCR share a simple Markdown chunker, and existing Artifact Workers prepare content -and indexes before committing a document revision together. Reuse existing core metadata schemas, CRUD, supervision, -and generic index storage; add only document-specific detail and target records. This is a proposed contract, not -released functionality. +Provide document knowledge bases through a Source plugin and the `document` and `rag` Artifact families. A Scope +contains multiple user-created rags; each document Source and whole-document Artifact belongs to exactly one rag. +OpenDAL captures immutable originals. Markdown and image OCR share simple chunking. Asynchronous operation requests +are immutable Sources consumed through the existing journal, cursor, and Worker framework. Commit each document +revision, its chunks, lineage, indexes, and consumption cursor atomically. + +Add one document chunk table and generic soft-deletion fields to `pc_sources`. Reuse Artifact storage and processing +schemas without a separate import/task/state platform. Expose content availability rather than durable per-file +execution status. This RFC proposes a contract; it does not describe released functionality. # Motivation Business descriptions and SOPs need passage retrieval over complete documents, exact provenance, explicit updates, -and predictable deletion. Memory extraction does not preserve every passage. The first implementation should cover -that workflow without a second task platform, a per-rag index-generation system, or duplicate Artifact master tables. +and predictable deletion. Memory extraction does not preserve every passage. The first phase should cover that +workflow with existing Source/Artifact infrastructure and explicit failure semantics. -Source snapshots and historical document revisions remain evidence. Knowledge-base retrieval is a derived projection, -maintained independently of existing Memory retrieval data and defaults. Reuse infrastructure without treating the -current plugin declaration as already sufficient for targeted ingestion, separate chunk storage, or deletion checks. +Source snapshots, accepted operation requests, and successful Artifact revisions serve different purposes. Keep +those distinctions without mutable task state in Source payloads. Retrieval is derived from committed chunks and +isolated from Memory indexes and configuration. Reuse requires actual family, read, projection, and Worker integration. # Guide-level explanation -1. Create a `rag` through standard Artifact creation in an existing Scope. -2. Select the rag and a local directory/file. The client uses a configured local OpenDAL Source plugin; users do not - supply Source IDs, namespaces, hashes, or document IDs. -3. Inspect the latest per-file processing status. Accepted input is not yet searchable content. -4. Search documents owned by the selected rag, or explicitly select multiple authorized rags. -5. Change a file and import again. Identical successfully processed input is skipped; changed content creates a new - Source and revision of the same logical document. -6. Edit or remove a chunk. Both create a new document revision; old revisions and their chunk content remain intact. - -Scope remains the authorization boundary. Source/document ownership is exclusive to a rag, not cross-rag sharing. -Importing the same file into two rags creates different Sources/documents even if their physical snapshots are deduplicated. -The initial release supports Markdown and independently imported text images using RapidOCR with ONNX Runtime. -Markdown image references are retained without fetching or OCR-processing them. SQLite, SeekDB, and OceanBase must -support the workflow, with one selected persistence backend per deployment. - -PDF, Office, plain TXT ingestion, semantic/LLM chunking, complex layout/table reconstruction, scheduled directory -synchronization, per-rag embedding spaces, independent online rag index cutovers, a full management UI, and a -large-corpus performance gate are out of scope. The UI can later use the per-file status contract. +1. Create an empty `rag` through standard Artifact creation in an existing Scope. +2. Select the rag and a local directory/file through the configured OpenDAL Source plugin. +3. View whether a usable document exists: generated, update needed, or not yet generated. No result does not prove failure. +4. Search selected authorized rags. A failed update leaves the previous committed content searchable. +5. Import changed files or explicitly reparse. Parsing restarts from a fixed original and commits a whole new revision. +6. Edit or remove a chunk asynchronously. The request is accepted first; a successful new revision retains old history. + +Users need not supply file hashes, namespaces, or document IDs. Scope remains the authorization boundary. Importing +the same file into two rags creates different logical Sources/documents, with optional physical snapshot deduplication. +Support Markdown and independently imported text images using RapidOCR with ONNX Runtime. Markdown image references +are retained without fetching or OCR. SQLite, SeekDB, and OceanBase must support the workflow, one selected backend +per deployment. + +PDF, Office, plain TXT ingestion, semantic/LLM chunking, complex layout reconstruction, scheduled directory sync, +per-rag embedding spaces, zero-downtime index cutovers, a task-management UI, durable per-file failure details, +restoration/permanent erasure, and large-corpus performance acceptance are outside the first phase. # Reference-level explanation @@ -55,386 +56,398 @@ large-corpus performance gate are out of scope. The UI can later use the per-fil ```text Scope - +-- rag K1 -- owns --> original Sources -- derive --> document revisions -- chunks - +-- rag K2 -- owns --> different Sources/documents, even for the same local file - -Source plugin: OpenDAL capture and immutable snapshot access -Document plugin: Markdown / OCR -> Markdown -> chunks, revisions and provenance -rag plugin: collection management, retrieval policy and index adaptation -Shared facilities: Source/Artifact APIs, Supervisor/Worker, transactions, database/search adapters + rag R1 + original Source S1 -> operation Source Q1 (import) -> document D@1 -> chunks + operation Source Q2 (edit D@1) -> document D@2 + successful edit evidence E2 + original Source S2 -> operation Source Q3 (reparse) -> document D@3 + rag R2 + separate original Sources, requests, and documents + +Source plugin: OpenDAL capture, snapshot access, original and trusted operation Source types +Document plugin: Markdown / OCR, chunks, revision writes, operation consumption and provenance +rag plugin: collection configuration, retrieval policy and chunk index adaptation +Shared facilities: Source/Artifact APIs, Supervisor/Worker, cursor, transactions, database/model adapters ``` -A rag is configuration and collection identity, not a Source-generated output. It can be empty. Its name/configuration -uses Artifact revisions; deletion uses existing head governance. There is no separate rag runtime table or runtime -status API. Parsing progress belongs to the imported file, not to rag configuration revisions. +The three logical plugins may ship in one package. The application service coordinates them; it is not a fourth +plugin. A rag can exist without Sources. Its configuration uses Artifact revisions, and deletion uses head governance. +There is no rag runtime table. Ownership is explicit in immutable Source payloads and document manifests, not inferred +from tags or evidence lineage. Each original, request, and document has one owner rag. -`document` represents a whole document. Its stable identity is scoped by `(scope, rag, collection, relative_path)`; -chunks are internal revision details. The server derives `collection` from the registered storage binding/instance -and normalized root, not a fresh scan ID. Source payloads contain immutable owner rag identity, original path, -relative path, media type, content digest, and a managed snapshot reference. Tasks snapshot processing configuration; -mutable task status and parsed text never enter Source payloads. Only the document pipeline directly consumes this -Source type, enforced at selection, execution, and commit. +The package owns independent embedding/index configuration. Explicit plugin settings win; installation may initialize +compatible missing values from the main path and persist the resolved profile and credential references. Do not copy +secrets into Artifacts or follow subsequent main-path changes. Parser/OCR/chunker configuration may vary by rag; +the initial embedding/index profile is plugin-level, shared by the document family within each Scope. Isolate indexes +by family, definition, and vector-space identity. Model/dimension changes use the existing family rebuild mechanism. -The three logical plugins may ship in one package. The knowledge-base package owns its embedding/index configuration, -separately from Memory or other main-path configuration. Explicit plugin settings win; otherwise installation may -initialize compatible values from the main path and persist a resolved configuration snapshot. Keep credential -references rather than copying secrets into Artifact content. Later main-path changes do not silently change the -plugin profile. Missing/incompatible settings fail activation. Parser/chunker settings may vary by rag; the initial -embedding/index profile is plugin-level, shared by its document family within each Scope. +Only the document pipeline may directly consume document originals; only its operation processor may execute +operation Sources. Enforce eligibility during selection, execution, and commit. Registering a new Source type alone +does not exclude it from existing generic consumers. Requests are neither ordinary generation input nor searchable text. -Reuse model invocation and SQL adapters, but isolate by family, index definition, and vector-space/profile identity. -No queries implicitly mix Memory rows with document rows. A plugin model/dimension change uses the existing family -rebuild mechanism, with its availability limitations, not a new per-rag publication protocol. +## 2. OpenDAL ingestion, identity, and duplicate detection -## 2. OpenDAL ingestion and duplicate detection - -Use the existing OpenDAL/`opendalfs` integration for local listing and reads. The plugin instance must run where the -selected local path exists; a remote Server cannot interpret an arbitrary client-local path. Resolve relative paths -against the configured root, reject escapes, and keep a stable normalization/symlink policy. Original Markdown bytes -and images are captured into managed immutable snapshots before Source acceptance. Hash the exact bytes saved; -never hash one read and process a later read of a changing file. Read errors or detected unstable capture are retryable. +Use OpenDAL/`opendalfs` for local listing/reads and immutable snapshots in a managed directory. The plugin instance +must run where the selected path exists. Fix root, relative-path, and symlink normalization; reject escapes. Capture +before acceptance, hash the exact saved bytes, and parse that snapshot, not a later read of a changing file. mtime/size +are hints, not proof of equality. Preserve the first canonical capture metadata when reusing an existing Source. ```text file_key = (scope_id, rag_id, collection_id, normalized_relative_path) +document_id = stable_hash(identity_version, file_key) content_digest = SHA256(captured raw bytes) -source_key = hash(source schema version, file_key, content_digest) -processing_key = hash(content_digest, parser/OCR/model versions and settings, - Markdown normalizer version, chunker version and settings) +source_key = stable_hash(source_schema_version, file_key, content_digest) +processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) index_key = hash(complete embedding inputs, plugin profile and projection versions) ``` -mtime/size may help select work but are not proof of identical content. Compare full identity fields on hash collision; -never truncate paths or merge them by digest alone. User-visible Source IDs are generated by the Source framework -using the plugin's deterministic identity rules. Reusing an existing immutable Source preserves its first canonical -capture metadata rather than rewriting mtime or annotations. +Derive collection from the registered storage instance/binding and normalized root, not a scan token. Verify full +identity fields on hash matches; never truncate paths or merge documents by digest alone. Original payloads store +owner rag, file identity, original path, document ID, media type, digest, and snapshot reference. The same document ID +is available before an Artifact exists; no reservation row is required. | Observation | Required behavior | | --- | --- | -| Same file/content/processing key, successful result | Reuse Source and document; no new revision; check index readiness separately | -| Same target already pending/running | Coalesce; do not launch another parse | -| Same input, previous processing failed | Retain pinned Source and allow bounded retry; a capture checkpoint is not processing success | -| Same path, changed bytes | Accept new Source; process a new revision of the same document | -| Same bytes, changed parser/OCR/chunker | Reuse Source; explicitly reprocess to a new revision | -| Only embedding/index profile changed | Reindex committed chunks without rerunning OCR | -| Different path or different rag, identical bytes | Different logical document and Source; optional physical snapshot reuse only | -| Deleted identity encountered | Reject implicit resurrection; no restore in phase one; require an explicitly new identity | - -Returning to previously seen bytes still compares against the current target/result: finding an old Source is not -proof the current document already represents it. Renames are new paths initially; missing files do not imply deletion. -Manual edits/removals must not be overwritten by an unchanged-file scan. Changed input or explicit reprocessing of -an edited document requires `manual_edits_policy=discard`; without it, retain the old committed revision and report -an actionable conflict. The input Source can already be captured while content processing remains blocked. - -Use Source `collect` capability discovery and existing add/status/control operations. A plugin-specific `scan_token` -in the capability input identifies one explicit scan target, generated by the client. A retried add with the same -input reuses that target; a new explicit import uses a new token but the same collection/file identities. The plugin -scans once per token and remains available for future targets; it does not periodically rescan. Existing Source -status describes collection, not full document processing or a batch history. New scans must consult document -processing state as well as capture checkpoints, so unchanged capture cannot hide downstream failures. - -## 3. Markdown normalization and simple chunking - -Both inputs produce a common Markdown view: +| Same file/content/processing profile, usable successful result | Reuse Source/document; skip parsing, check index readiness separately | +| Equivalent request still unconsumed | Coalesce when found in the unconsumed journal; racing duplicate imports recheck success before writing | +| Same input, no successful result | An explicit retry may create a new request; a capture checkpoint is not processing success | +| Same path, changed bytes | New original Source, same document ID, whole-document revision on success | +| Parser/OCR/chunker changes | Reuse original Source; explicitly request reprocessing | +| Only embedding/index changes | Reindex committed chunks without OCR | +| Different path/rag, same bytes | Different logical Source/document; optional physical snapshot reuse | +| Unchanged original after manual edits/removal | Preserve the manual revision; do not compare its edited text hash as if it were the original hash | +| Reprocessing an edited document | Require explicit `manual_edits_policy=discard`; otherwise retain current content and reject the conflict | + +Reverting to old bytes can reuse an older Source, so desired input follows the latest accepted import/reprocess request, +not the largest original Source journal position. Finding a Source is not proof that the current document matches it. +Renames create new identities initially; absent files do not imply deletion. Deleted Source identities and retired +document heads must not be silently resurrected. + +Reuse Source `collect` discovery/add/status/control. A client-generated `scan_token` in plugin input identifies one +explicit scan; retrying that input reuses its collection target. A new explicit scan has a new token but the same +file identities. Scan once per token; do not imply periodic sync or that repeated add restarts a stopped target. +Collection status describes acquisition only. Scans consult successful document results as well as capture checkpoints. + +## 3. Markdown normalization and chunking ```text -Markdown bytes -> markdown-it-py structure / original-byte mapping --+ - +-> rule-based chunks -Image -> RapidOCR -> text lines/regions -> normalized Markdown -----+ +Markdown bytes -> markdown-it-py structure / byte mapping ----+ + +-> rule-based chunks +Image -> RapidOCR text/regions -> normalized Markdown --------+ ``` -For OCR, preserve actual text, order, confidence and original-image regions, accounting for preprocessing transforms. -Markdown conversion escapes syntax and groups lines/paragraphs; it does not invent headings, repair text with an LLM, -or reconstruct complex tables. Keep normalized-text spans mapped to OCR lines and image regions. Normalized Markdown -is derived processing content, never a replacement for the image Source. A locator must state its actual precision. +OCR preserves actual text, order, confidence, and original-image regions, including preprocessing transforms. +Normalization escapes Markdown syntax and groups lines/paragraphs; it does not invent headings, use LLM correction, +or reconstruct complex tables. Map normalized spans back to OCR lines and image regions, stating locator precision. +Derived Markdown never replaces the original image Source. -Use headings, paragraphs, lists, and code blocks; merge short blocks up to `max_chunk_chars`, split oversized blocks -at sentence/length boundaries, and optionally retain `overlap_chars` at split boundaries. Validate overlap is smaller -than the maximum. Preserve heading paths, order and continuation flags; do not require a standalone section-tree -subsystem. Before embedding, enforce the actual model token budget, including any heading/prefix context; do not -silently truncate. Chunker changes that alter boundaries are versioned configuration changes. +Use headings, paragraphs, lists, and code blocks. Merge short blocks up to `max_chunk_chars`; split oversized blocks +by sentence/length, optionally using `overlap_chars`. Preserve heading paths, language, and continuation flags. +Overlap must be smaller than the maximum. Example values 1200/100 need validation; actual embedding token limits, +including heading/prefix context, must be enforced without silent truncation. -Source media validation, UTF-8 errors, bad/unsupported images, no recognized text, missing OCR models, excessive -pixels, and timeouts have explicit outcomes. Pin/test real RapidOCR and ONNX/model versions. Normalized Markdown may -be computed transiently; an independent parsed-document cache is not required. Chunks store effective text and -bounded source mappings, not vectors. The Artifact manifest remains bounded and does not embed all chunks. +Validate formats, UTF-8, image decoding/pixel limits, OCR models, timeouts, and no-text outcomes. Pin/test real RapidOCR, +ONNX, and model versions. Empty OCR is not successful empty-document ingestion. An explicit removal of the last chunk +is allowed. No separate section-tree, parsed-node table, or complete Markdown cache is required. Store bounded source +mappings in chunk metadata; keep vectors out of canonical chunks and full text out of the Artifact manifest. -## 4. Persistence: unchanged core schemas and three supporting tables +## 4. Persistence: one detail table and Source lifecycle fields -Existing core metadata table definitions are unchanged by this proposal. New family records, declarations, and -indexes use their established schemas. This is a constraint on migrations, not a claim that code changes are unnecessary. +Do not add `pc_document_imports` or `pc_document_source_states`. Source payloads carry immutable identities/requests; +Artifacts carry successful revisions; existing processing tables coordinate consumption. Do not replace the removed +tables with unbounded maps in rag content, Scope settings, checkpoints, or cursors. -| Reuse | Purpose and required code integration | +| Reuse | Responsibility and structural change | | --- | --- | -| `pc_sources`, Source journal, connector checkpoints | Immutable inputs, capture identity and acquisition progress | -| `pc_artifacts`, `pc_artifact_heads` | rag configuration, document revision manifest, active/retired state and governance CAS | -| `pc_artifact_lineage_sources`, locators, Artifact lineage, tags | Root input, system edit Source, base revision and tags; not mutable membership | -| `pc_artifact_processing_intents`, leases, binding state | Durable wakeup, explicit request generations, execution ownership and registration fences | -| `pc_artifact_search_states`, coverage, changes | Existing Scope/family build coordination and current-revision index maintenance | -| `pc_artifact_search_text`, vectors, vector spaces/index definitions | Fragment-level retrieval projections; `family=document`, `fragment_id=chunk_id` | - -Do not add `pc_rag_runtime`, per-rag generations/publications, a general jobs/receipts system, or separate nodes/directory -master tables. Do not store state in unrelated Scope settings or change Source payloads to simulate mutable metadata. -Document ownership is explicit, not inferred from tags or evidence lineage. - -The three supporting tables below are a proposed implementation baseline. Include UTC timestamps, byte-exact -identity comparison, bounded JSON metadata and backend-safe key lengths. Migrations must check actual layouts on -all three backends; equivalent existing storage may replace a table only with matching uniqueness and recovery semantics. - -| Table | Primary/unique keys | Minimum fields and role | +| `pc_sources` | Originals, operation requests, successful edit evidence; add generic lifecycle fields below | +| Source journal/heads, connector checkpoints | Acceptance order and acquisition progress; unchanged schema | +| `pc_source_cursors` | Document binding's contiguous scan position and CAS generation; unchanged schema | +| Processing intents, leases, binding state | Scope/binding wakeup, invocation generations, execution fences; unchanged schema, not per-file tasks | +| `pc_artifacts`, `pc_artifact_heads` | rag configuration, document manifests, current revision and retirement/governance; unchanged schema | +| Source/Artifact lineage, locators, tags | Original input, request, base revision, successful edit evidence; existing schema | +| Artifact search states/coverage/changes/text/vectors | Current-revision fragment indexes and build coordination; existing facilities plus a chunk projection adapter | + +Add these columns to `pc_sources`: + +| Column | Type/default | Meaning | | --- | --- | --- | -| `pc_document_imports` | PK `(scope_id, document_id)`; UQ `(scope_id, rag_id, collection_id, path_hash)` | Full relative path, binding name, current/target SourceRef and digest, processing/configuration snapshot and fingerprint, target generation, operation (`import/reprocess/edit`), bounded pending edit, request ID/digest, state/stage, attempt, retry time, lease token/expiry, result revision and error; combines identity reservation, membership and latest per-file work | -| `pc_document_chunks` | PK `(scope_id, document_id, revision, chunk_id)`; UQ `(scope_id, document_id, revision, ordinal)` | Text, content digest, heading path, continuation/overlap metadata, normalized spans and original byte/image locators, origin, edit/base references; complete immutable revision snapshot | -| `pc_document_source_states` | PK `(scope_id, source_type, source_id)` | Immutable owner `rag_id`, document/file identity, `state=active/deleted`, deletion generation/time; mutable lifecycle alongside the original Source, including its system edit Sources | - -Reserve a document ID before parsing without requiring an Artifact head to exist. Once committed, all detail keys -resolve to `family=document` in the same Scope; each Source's owner matches the reservation and immutable payload. -The manifest contains owner rag, root SourceRef, schema/processing fingerprint, chunk count/digest and manual-change -indicator. A revision with 100 chunks has one manifest and 100 rows; removing a chunk creates a new manifest and 99 -rows without touching the original 100. Copies of unchanged rows may be prepared efficiently, but incomplete snapshots -must never become visible. Old revisions are addressed exactly, not by interpreting today's head. - -Index imports by `(scope, rag, document_id)`, pending work by binding/state/retry time, chunks by revision/ordinal, -and Source state by `(scope, rag, document_id)` for deletion fan-out. Verify existing reverse lineage access paths -for root-source revocation. Hash keys retain and compare full original identities. Source row ownership is immutable; -status/progress never changes it. The imports table preserves the latest target/result, not an unlimited batch or -command history. Errors before a Source is accepted belong to collection diagnostics. A complete durable batch -history would require an explicitly scoped extension, not an unbounded JSON array in a metadata row. - -## 5. Existing Workers and atomic content/index commit - -The application service coordinates the three plugins; it is not another plugin or service. Source acceptance/reuse, -Source lifecycle initialization, document target reservation/update, and `processing_intents.request()` commit -atomically. A durable target can therefore be recovered even if a wakeup notification is lost. The source-only -submission paths must call this same acceptance capability; they cannot bypass target validation. - -Supervisor dispatch remains Scope/binding based. The document processor selects pending import rows rather than -broadcasting every Source to every rag. Explicit requests handle retry/reprocess with no new Source journal entry; -do not fabricate a positive `source_through` or advance a Source cursor for target-only work. +| `lifecycle_state` | Short string, NOT NULL, default `active` | `active` or `deleted`, one-way transition initially | +| `deleted_at` | Nullable UTC timestamp | First deletion time; repeat deletion does not refresh it | + +Backfill existing Sources as active. Payload, identity, and journal position remain immutable. Lifecycle metadata is +excluded from content hashing. Use row locking/conditional updates and consistent lock ordering against document +commits; no separate Source deletion-generation column is required initially. Adapt add/get/list, evidence and generation +access, and family reads. Duplicate add of a deleted identity must not return usable content or reactivate it. Internal +migration/cascade scans may include deleted rows; public reads cannot bypass deletion. Verify additive migrations on +SQLite, SeekDB, and OceanBase rather than treating Artifact retirement as existing Source soft-deletion support. + +The only new domain table is `pc_document_chunks`: + +| Constraint/fields | Design | +| --- | --- | +| Primary key | `(scope_id, document_id, revision, chunk_id)` | +| Unique order | `(scope_id, document_id, revision, ordinal)` | +| Content | `text`, `content_digest` | +| Structure | Heading path, continuation/overlap metadata | +| Provenance | Normalized spans, original byte/image locators, origin/verbatim, base/edit references | + +Use backend-safe keys and bounded metadata. Each revision is a complete immutable chunk snapshot: removing one of +100 chunks produces a new manifest and 99 rows, preserving the original 100. Manifest fields include owner rag, +file identity, root SourceRef, schema/processing fingerprint, chunk count/digest, manual-change flag, and +`applied_request_ref`. History uses exact revisions, not today's head. + +Initially, membership and availability may require paginated Scope/type scans and payload decoding plus exact +Artifact reads by deterministic document ID. Do not assume canonical payloads already have queryable JSON owner/path +indexes. Filtered pagination tracks the scan position without losing later matches. Validate ownership and full identity +at writes/reads. These scans have costs; no large-scale performance claim is made. Additional projections require measured +need, not an implicit reintroduction of a task table. + +## 5. Operation Sources, Workers, and transaction boundaries + +A trusted application service creates a dedicated operation Source type, illustrated as `document_operation`; +originals are illustrated as `document_file`. These are plugin registrations, not new storage tables. A request stores +owner rag, document ID, operation, root SourceRef, fixed processing configuration/fingerprint, request ID, base revision, +and bounded edit/discard parameters. Initial import may have no base; edit requires an existing base. Do not store +mutable state, attempts, errors, or a future output revision in its payload. Ordinary user metadata cannot forge commands. + +Import/reprocess regenerates the whole document from a fixed original. Edit supports `replace_text` and `remove`. +Existing `ContentSourceInternal` binds successful `artifact_create`/`artifact_replace` evidence to an exact revision; +it cannot represent an unexecuted command. Preserve that successful-result contract and use the separate request type. + +Accept/reuse the original, insert the request, and call the document binding's `processing_intents.request()` in one +transaction. Only a newly accepted request schedules new work. Extend Source/binding notification integration explicitly; +the current SourceRepository does not automatically discover this proposed processor. + +Request identity is deterministic within Scope/rag/document/operation and client `request_id`. Identical canonical +payload replays return the accepted request; different payload under the same identity conflicts. Replaying a consumed +request never reruns it. An explicit retry uses a new request ID, possibly the same original Source. Incrementing an +invocation counter alone cannot rerun an input already passed by the cursor. ```text -pending -> running -> succeeded - +--> retry_wait -> pending - +--> failed / blocked -new target -> increment target generation; an old attempt becomes superseded -rag/document/Source deletion -> affected target cancelled; no further commit +accept request Source + processing intent atomically + | +existing Worker scans the document binding's journal window in order + | +prepare chunks/embeddings outside the transaction + | +commit document + chunks + lineage + indexes + cursor atomically ``` -Only one active target is processed per logical document. Identical pending input coalesces; a newer accepted file -version can supersede an older parse. Manual edits require no conflicting pending mutation. Persist the operation, -pinned input/configuration, base revision, and latest request token so restart can retry the same work. Replay of the -current token/digest returns current status; different content under that token conflicts. Superseded token versions -cannot recreate work. There is no promise of indefinite historical receipt replay. +Process sequentially within a Scope/document binding, using bounded windows and existing fences/cursor CAS. Ignore +unrelated Sources while advancing the contiguous scan boundary. No per-file queue or latest-request-wins cancellation +is promised. Requests pin their base; if an earlier operation changes the head, a later request may conflict instead +of silently rebasing. Users refresh and submit a new request. Source acceptance during execution does not mutate the +running request. Scope invocation acknowledgement follows existing `ScopeInvocation` rules; partial work must not +mark an entire window clean. + +The cursor records consumption, including skips, not success. Successful revisions identify their request through +`applied_request_ref` and lineage. There is no durable per-request failure receipt. + +| Outcome | Cursor and recovery | +| --- | --- | +| Input-specific parse/OCR/configuration failure or base conflict | Log sanitized identifiers/error, advance past that request under the execution fence, retain old content, continue other inputs | +| Transient request-local error | Optional bounded in-process retry, then the same failure/skip rule; no durable attempt counter | +| Database failure, index rebuild, or system-wide model unavailability | Do not advance this request; reuse Supervisor backoff/recovery and report binding-level unavailability | +| Process exits before commit | Cursor has not advanced; re-execute the fixed request after recovery | +| Process exits after successful commit | Content and cursor are already committed; do not create another revision | +| Crash between failure logging and skip commit | The request may run again; duplicate diagnostics are allowed | + +Logs follow existing observability contracts and exclude content, credentials, and sensitive paths. Logs are not a +recovery dependency. A consumed failed request requires a new explicit request to retry. Runtime task status or a +request timeout cannot establish permanent failure. | Boundary | Work | | --- | --- | -| Outside transaction | OpenDAL snapshot capture; parsing/OCR; Markdown/chunk construction; embedding and prepared index projections | -| Acceptance transaction | Validate owner/lifecycle and preconditions; accept/reuse Source and target state; request existing processing intent | -| Content transaction | Recheck target generation, base head, owner/Source lifecycle, plugin profile/build and Worker fences; commit manifest, complete chunks, lineage, any system edit Source, head, prepared indexes and successful target state together | -| Deletion transaction | Retire parent Artifact or mark Source deleted; invalidate the owned targets; record recoverable fan-out state using existing invocation plus target rows | - -Models and DDL do not run while holding the content transaction. The chunk projection adapter prepares from the -chunk snapshot rather than expanding the bounded manifest as if it contained full text; validate both snapshot -and projection fingerprints at commit. Existing generic JSON-field projection is not sufficient without this adapter. - -A failed normal update leaves the previous committed head and indexes; no new readable-but-unindexed revision is -created. History may be read independently but retrieval uses the current indexed revision. If the shared document -family index is rebuilding or unavailable, defer new document commits and expose unavailability. Do not silently -use the generic content-only-during-rebuild path, fall back to Memory retrieval, or promise zero-downtime cutover. -Rebuild reads committed chunks, not OCR again. SQLite, SeekDB and OceanBase must prove the transaction/read behavior -through their real adapters; native ANN limitations require filtered exact retrieval or an explicit capability failure. - -## 6. Editing, chunk removal, and soft deletion - -An edit command supports `replace_text` and `remove` for an existing chunk, with document `If-Match`. The worker -constructs a complete new revision, revalidates count/order/digest, prepares changed indexes, and commits atomically. -Deleting the last chunk is allowed: an empty effective document has zero indexed fragments but remains a readable -manifest with provenance. Unchanged chunks keep logical IDs; rechunking assigns new IDs. Every citation includes -revision. A remove operation affects the current snapshot only, never physically deletes historical chunk rows. - -At successful commit create the system Content Source with `role=lineage_only`, `operation=artifact_replace`, exact -new revision, base revision and edit/removal command. It records the modification and is not ordinary parser input. -Preserve the root document Source dependency explicitly; generic replacement does not imply this automatically. -Mark changed text `origin=manual_edit`, `verbatim=false`; original coordinates are edit evidence, not proof those -words occur in the image. Removing a chunk also counts as a manual change, protected against silent reparse overwrite. -Unchanged actual embedding input/profile may reuse computation, but new revision mappings still replace old entries. - -| Delete operation | Persisted state and consequences | +| Outside transaction | Snapshot capture; parsing/OCR; complete chunk snapshot; embedding and index projection preparation | +| Acceptance transaction | Authorization, ownership/lifecycle/base checks, Source/request acceptance, processing intent | +| Successful content transaction | Recheck Worker/cursor/base/owner/root/index fences; commit manifest, chunks, lineage, successful edit evidence when needed, head, indexes, and cursor | +| Failure-skip transaction | Revalidate execution/cursor fences and advance the contiguous boundary; no document write or successful edit evidence | +| Deletion transaction | Mark Source lifecycle or retire Artifact head; parent/root checks block concurrent publication | + +Models and DDL run outside the content transaction. Chunk projections are prepared from chunks, not full-text JSON +inside the manifest. Validate snapshot and projection fingerprints. New content and indexes become visible together; +failed updates retain the previous head/indexes. During family rebuild defer new document commits, not the generic +content-only path. Rebuild committed chunks without OCR, with explicit unavailability rather than Memory/full-text +fallback or a zero-downtime promise. Verify real transaction behavior on all backends, including SQLite write locking; +ANN limitations need filtered exact retrieval or a clear capability failure. + +## 6. Editing, chunk removal, and deletion + +Validate edit `If-Match` both at acceptance and commit. A successful edit writes a whole new snapshot. Unchanged chunks +keep logical IDs; rechunking assigns new ones; citations always include revision. Removing the last chunk leaves a +readable zero-chunk manifest and no current index fragments. No removal physically deletes old chunk rows. + +At success, create a system Content Source with `role=lineage_only`, `operation=artifact_replace`, and the exact new +revision, recording request/base/root provenance. Preserve the original Source dependency explicitly. Mark edited +text `origin=manual_edit`, `verbatim=false`; old image coordinates are edit evidence, not verbatim proof. Removal +also counts as manual modification. Explicit reparse must authorize discarding manual changes. Unchanged complete +embedding inputs may reuse computation, but index mappings must identify the new current revision. + +| Delete operation | Behavior | | --- | --- | -| Source | Mark sidecar state deleted without mutating payload. Retire a document whose current input is that Source; revoke all matching historical revisions and edit-Source reads. A current revision solely derived from a replacement Source survives | -| Document | Retire its Artifact head; block all its revisions/chunks and pending work; original Source is not deleted | -| rag | Retire its head, immediately block all owned content, then durably mark all owned Source versions and document heads deleted/retired, including documents that never finished processing | -| Chunk | Create a new document revision without that chunk; historical content stays intact | - -Retirement uses existing `lifecycle_state=retired` and governance CAS; do not add a second rag/document deletion flag. -Source deletion uses the sidecar because `pc_sources.payload` is immutable. Repeated deletion is idempotent. -A reserved document with no head is cancelled in its import row with terminal reason `document_deleted`; do not -create an empty Artifact just to retire it. That identity cannot be silently revived by another scan. Deleting a -pending replacement Source cancels its target but does not retire a committed revision based on a different Source. -Large cascades may finish in bounded batches: the retired rag and persistent ownership make incomplete fan-out -rediscoverable, while parent checks immediately prevent reads/commits. Source ownership is never shared across rags, -so deleting one rag cannot delete another's Source. Keep OpenDAL snapshots and canonical/historical content; do not -delete user files. Restore and permanent erasure are not offered initially. - -Search and generic exact/history/chunk reads check owner rag, document head and that revision's root Source. -Historical base-revision links do not make a fully reparsed replacement transitively dependent on an old Source. -System edit Sources also check their target document/rag. Original Source access checks its own state and owning -rag; deleting only a document leaves that original Source readable, deleting its rag does not. Family-specific read -validation must enforce these rules; generic retirement alone can otherwise leave exact reads available. - -Search indexes are derived, not historical evidence. Reuse their existing replacement/removal/rebuild maintenance; -soft deletion preserves business data, not a promise that every historical index entry is retained. Retained stale -entries must be excluded before ranking, including during cascade recovery. Parent/Source checks and commit fences -are mandatory regardless of physical index cleanup. Already delivered responses cannot be recalled. - -## 7. Unified API contract - -All routes below are design proposals or extensions; current schemas do not already support every family/filter. -Implement changes in `openapi/powercontext.yaml` and regenerate bindings. Reuse existing permissions, error envelopes, -Artifact/Source references, pagination, ETags and SDK/MCP operation mappings. Do not route document files through the -current generic create-Source command, whose schema only accepts built-in content; use the Source plugin protocol. - -Let `R=/v1/scopes/{s}/artifacts/rag/{r}` and `D=/v1/scopes/{s}/artifacts/document/{d}`. - -| Operation | Reuse or narrow extension | Semantics | -| --- | --- | --- | -| Create/configure rag | Existing POST `/v1/scopes/{s}/artifacts`, GET/PUT `R`, revisions/tags | `family=rag`; complete config replacement and existing If-Match; no parser work for empty creation | -| Import directory/file | Existing POST `/v1/source-management/add` with discovered collect capability and instance | Plugin input carries owner rag and local root/file; Source receipt retains its existing collection semantics, not a new rag import/job envelope | -| Collection status/control | Existing source-management status and target/instance controls | Do not claim collect add reschedules a stopped target or status is full batch history | -| Sources/documents | Existing Source list/get; Artifact list/get/history | Add validated owner-rag filtering where missing; document GET returns bounded manifest, not all chunks | -| Current file progress | New GET `R/processing`, cursor and state filter | Latest per-file target, stage, attempts/error, request generation and committed revision, including unprocessed reservations | -| Retry/reprocess | New POST `D/processing`; failed first imports use reserved document ID even without a head | `action`, `expected_target_generation`, `request_id`, optional discard policy; `202` current target receipt | -| Read chunks | New GET `D/revisions/{rev}/chunks` | Existing items/next_cursor convention; exact-revision effective chunks and source locators | -| Edit/remove chunk | New POST `D/edits` | Document If-Match, bounded typed operation and request_id; `202` pending target, new revision only after atomic success | -| Retrieve | Existing POST `/v1/scopes/{s}/artifacts/document/search` | Existing query/mode/limit/fusion; required validated `filters.rag_ids`; extend optional matched fragments without replacing complete Artifact results | -| Soft-delete Artifact/Source | Add DELETE to existing exact Artifact/Source resource routes | Family writer/Source lifecycle service validates ownership; Artifact `expected_generation` (governance CAS); reuse scope.contribute for document, scope.admin for rag/Source | - -Rag config stores title/summary and parser/OCR/chunker settings or references, not runtime progress, members, or -main-path embedding configuration. A config change affects subsequent accepted targets; existing documents change -only through explicit reprocessing. Manual change protection still applies. - -Create example, using the standard Artifact envelope: +| Original Source | Set Source lifecycle deleted; retire a document still rooted in it and revoke dependent history. A revision fully reparsed from another root survives | +| Document | Retire its head; block all revisions/chunks and future commands, leaving original Sources active | +| rag | Retire its head, immediately block all owned content, then recoverably mark all owned Sources (including requests/edit evidence) and document heads deleted/retired | +| Chunk | Commit a new revision without that chunk, retaining history | + +Reuse Artifact `lifecycle_state=retired` and governance CAS. Original Source payloads/snapshots and historical business +content remain stored; user files are untouched. No restore or permanent erase initially. An imported file without a +head is deleted through its original Source; document DELETE returns not found rather than manufacturing a placeholder +Artifact. A deleted pending replacement Source must not retire an older committed version based on a different root. + +Check owner rag, document head, and the exact revision's root on search and generic/exact/history/chunk reads. +Historical base links do not transitively revoke a full reparse from a replacement root. Original Source reads check +its state/owner; deleting just a document does not hide its original. Request/edit evidence reads also check the target +document to prevent retained manual text from bypassing deletion. Deleting a request blocks unconsumed execution, +not an already committed edit: content validity is governed by root/document/rag, not a retroactive cancellation. + +Generic retirement alone may still allow exact reads; add family guards. Large rag cascades rediscover remaining work +from the retired parent and immutable ownership, including deleted rows internally, without a cascade job table. +Exclude invalid rows before ranking even while fan-out is incomplete. Derived indexes retain existing replacement, +removal, and rebuild semantics; preserving business history does not promise every historical index entry stays intact. + +## 7. Availability and unified APIs + +| Display | Derivation | +| --- | --- | +| Generated | A usable committed revision matches the selected original/configuration; valid manual changes are preserved | +| Update needed | A usable older revision exists but desired original/configuration differs; it may still be searchable | +| Not yet generated | Source accepted, no usable successful revision; could be unstarted, running, or failed | +| Deleted | Source or owning Artifact lifecycle invalid; no retained text, normally excluded from lists | + +Desired input uses the latest accepted import/reprocess request, or the accepted original if none exists. Manual edits +are not raw-file mismatches. Rag configuration changes affect future requests and may indicate reprocessing is needed; +they do not automatically enqueue it. Do not expose per-file stages, percentages, attempt counts, durable errors, or +infer success from collection completion/cursor advancement. Binding diagnostics and index availability stay separate. + +Reuse existing permissions, errors, references, pagination, ETags, and SDK/MCP operations. Implement necessary contract +changes in `openapi/powercontext.yaml` and regenerate bindings. The current generic create-Source accepts built-in +content; document files go through the Source plugin protocol. Let `R=/v1/scopes/{s}/artifacts/rag/{r}` and +`D=/v1/scopes/{s}/artifacts/document/{d}`. + +| Operation | Existing route or necessary extension | +| --- | --- | +| Create/configure rag | Existing POST `/v1/scopes/{s}/artifacts`, GET/PUT `R`, revisions/tags; full replacement and existing preconditions | +| Import/control | Existing POST `/v1/source-management/add`, collect capability/instance, existing status/target/instance controls | +| List files and available results | Existing Source list/get and Artifact list/get/history, validated owner-rag filters, helper join by document ID; no `R/processing` task list | +| Explicit reparse | POST `D/processing`, `source_ref`, `action=reprocess`, `request_id`, optional configuration/discard; 202 request acceptance | +| Edit/remove chunk | POST `D/edits`, current `If-Match`, typed bounded operation and request ID; 202 request acceptance | +| Read chunks | GET `D/revisions/{rev}/chunks`, exact revision, `items/next_cursor` | +| Search | Existing POST `/v1/scopes/{s}/artifacts/document/search`, existing query/mode/limit/fusion, validated `filters.rag_ids` | +| Soft-delete | DELETE on existing exact Source/Artifact routes; Artifact governance `expected_generation`, one-way Source lifecycle | + +Reparse with an existing head requires `If-Match`; without a head, use the deterministic document ID and +`If-None-Match: *`. Validate that Source ownership/file identity resolves to that ID, and recheck the base at execution. +Do not return Scope invocation generations as document target generations. Reuse `scope.contribute` for document +operations and `scope.admin` for rag/Source deletion, with existing read authorization. + +Create rag: ```json -{"family":"rag","content":{"title":"Operations SOPs","summary":"Runbooks and screenshots","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +{"family":"rag","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} ``` -Directory collection example; capability/instance names and settings are illustrative discovered deployment values: +Directory collection; capability/instance names are illustrative deployment-discovered values: ```json {"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} ``` -The target rag reference is validated at acceptance; ownership persists by rag ID, while processing pins accepted -configuration. A scan token is not a document identity and does not change the Source protocol's top-level schema. -A client retries a scan with the same token; a deliberate rescan uses a new one. - -Chunk removal example, POST `D/edits` with the current document ETag: +Remove a chunk with POST `D/edits` and the current document ETag: ```json {"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} ``` +The 202 receipt states durable acceptance, not pending status or a future revision: + ```json -{"document_id":"doc-1","request_id":"edit-03","target_generation":4,"state":"pending","committed_revision":2} +{"accepted":true,"document_id":"doc-1","request_source":{"source_type":"document_operation","source_id":"request-03"},"current_revision_at_accept":2} ``` -The receipt does not invent revision 3 before commit. GET processing later reports success and the committed new -revision, or failure with revision 2 unchanged. For replacement, use `kind=replace_text` plus `text`; do not represent -partial operations as complete content in generic PUT. Repeating the current request ID/digest reuses its target; -conflicting or superseded requests return conflict/precondition errors rather than silently reapply. +`current_revision_at_accept` is an observation, not the output. Confirm success through a revision's +`applied_request_ref`; no matching revision does not prove failure. For a new execution, refresh preconditions and +use a new request ID. Identical replay returns the original acceptance fact, not a fresh execution result. -Single-Scope retrieval reuses the generic request: +Explicit reparse, with `If-Match` for an existing document and authorization to discard manual changes: ```json -{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} +{"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} ``` -`results` still contains complete document Artifact manifests and lineage. Add an optional typed `matches` field to -search items for bounded exact chunk hits: chunk ID, text, locator, origin/verbatim, and fragment scores. It is a -response projection, not part of persisted Artifact content. `limit` continues to bound returned Artifacts; -per-document fragment count has a separate capability limit. Validate only advertised document filters/options; -unsupported rerank is an explicit capability error. Neither unknown filters nor omitted rag selection may widen scope. - -For cross-Scope queries, the client/helper accepts explicit `(scope, rag)` targets, authorizes all of them, groups -calls to the same existing search operation and fuses ranks. Preserve document/chunk identity and per-target errors; -do not compare incompatible raw scores or silently return no matches on failure. This phase does not add a separate -`/rag/query` wire protocol. HTTP, Python and MCP use the same family operations, with bounded orchestration where needed. - -| Condition | Response | -| --- | --- | -| Missing/stale document/config ETag | Existing 428/412 precondition errors | -| Conflicting target generation/request, pending edit or discarded-edit policy missing | 409 with actionable code | -| Deleted resource or evidence | 410 after authorization; no retained text in errors | -| Invalid format/config/oversized input | 422; transport may reject oversized bodies with 413 | -| Index/model unavailable or rebuilding | 503; no silent full-text-only downgrade or alternate-family search | -| Accepted processing fails | Latest target becomes failed/blocked/retry_wait; Source acceptance remains distinct from success | - -Use the existing error shape, for example: +Search selected rags in one Scope: ```json -{"error":{"code":"resource_deleted","message":"The requested document is unavailable.","details":null}} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} ``` +Search results retain complete bounded document manifests and lineage. Add optional typed `matches` for bounded exact +chunk hits, including revision/chunk ID, text, locator, origin/verbatim, and scores. This projection is not stored in +Artifact content. `limit` counts documents; fragments per document have a separate cap. Reject unsupported filters or +rerank options explicitly; missing rag selection must not broaden the search. Cross-Scope helpers authorize explicit +`(scope, rag)` targets, invoke the same per-Scope search, rank-fuse, and retain target errors/identities. Do not compare +incompatible raw scores or introduce a separate `/rag/query` protocol. + +At acceptance use existing 428/412 preconditions, 409 payload/discard conflicts, authorized 410 deletion, 422 validation +(or transport 413), and 503 service unavailability with the existing `error.code/message/details` envelope. After 202, +request-local failures/conflicts follow the log-and-consume rule; there is no durable error-status endpoint. + ## 8. Implementation and acceptance -Framework reuse still requires a typed document Source acceptance hook, per-file selection in Workers, a -chunk-backed projection adapter, filtered retrieval before top-k, lifecycle checks on all reads, and same-transaction -family writers. Reuse tables does not justify storing full documents in manifests or treating generic JSON projection -as already sufficient. No changes to core metadata columns are planned; additive domain migrations and OpenAPI -extensions must be reviewed if the implementation discovers a genuine gap. +Reuse requires Source lifecycle migrations/read guards, trusted request admission, consumer eligibility, document +binding notification, journal selection/cursor transactions, chunk projection, and ownership filtering before top-k. +It does not imply a zero-change framework or existing support for all proposed routes. -On each of SQLite, SeekDB and OceanBase, test the following through public operations: +Run the same public workflow against SQLite, SeekDB, and OceanBase: -- Create two rags in one Scope and another in a different Scope; same file imports have exclusive owners and no query leakage. -- Capture Markdown from a pinned `oceanbase/oceanbase` commit and real OCR fixtures; preserve image references and accurate locators. -- Identical success skips, failed identical input retries, changed bytes revise, config changes reprocess, and embedding-only changes do not OCR. -- Reject stale workers and conflicting edits; restart from durable current targets; content/index failure exposes no half-published revision. -- Delete a chunk by revision replacement, including the last chunk; old snapshots remain complete and current indexes exclude it. -- Source/document/rag soft deletion, cascading completion after restart, historical/edit-Source read checks, and new-Source revisions surviving old-Source deletion. -- Plugin config initialization from compatible main settings without live coupling; isolated indexes and explicit unavailable rebuild behavior. -- Core schema compatibility, filtered hybrid search, pagination and contract generation; mocks alone do not establish real backend/OCR support. +- Multiple rags and Scopes, exclusive file ownership, authorized selection and no cross-rag results. +- Markdown from a pinned `oceanbase/oceanbase` commit and real OCR fixtures with accurate provenance. +- Source migration backfill, immutable payload, deleted replay rejection, and exact/history/evidence read guards. +- Successful duplicate skipping, failed-input retry with a new request, configuration reparse, embedding-only rebuild. +- Atomic request/intent admission, restart recovery, atomic content/cursor commit, no rerun on request replay. +- Input-local failure consumption versus system-wide failure retention; cursor advancement never means file success. +- Async base conflicts/late Workers, no successful edit evidence on failure, manual-edit protection. +- Versioned chunk removal including the last chunk, complete history and correct current indexes. +- Source/document/rag deletion races, recoverable cascade, replacement-root independence. +- Independent plugin configuration, index isolation, rebuild unavailability, pagination, contract generation and SDK/MCP parity. -Use existing #2441 for ownership/ingestion, #2442 for processing/content/index integration, #2443 for retrieval/interfaces, -and #2444 for diagnostics/three-backend acceptance. One implementation branch/PR may deliver these four review stages. -This RFC PR does not close implementation issues. Do not add issues or claim large-corpus capacity from functional fixtures. +Mocks do not establish real backend/OCR support. Use #2441 for ingestion/ownership/Source lifecycle, #2442 for processing, +requests/chunks/atomic writes, #2443 for retrieval/interfaces, and #2444 for diagnostics/acceptance. One implementation +branch/PR may deliver these stages. This RFC does not close implementation issues or establish large-corpus capacity. # Drawbacks -Complete chunk snapshots amplify storage and writes. Retaining soft-deleted originals/history requires capacity -monitoring. Shared document-family rebuilds can interrupt retrieval across rags in one Scope. Latest per-file state -is simpler than a task center but lacks complete batch/command history. Plugin-specific read/projection/acceptance -integration is still substantive work even with unchanged core schemas. OCR packaging/platform support needs testing. +Operation Sources grow the journal; complete chunk snapshots and retained deleted data consume storage. Sequential +consumption can cause head-of-line waiting. Availability lacks durable per-request failures, and initial owner/request +filtering may scan payloads. Family rebuilds can interrupt several rags. These are explicit first-phase tradeoffs; +Source lifecycle and consumer/projection integration still require meaningful implementation work. # Rationale and alternatives -- A Scope per knowledge base couples collection organization to authorization; multiple rag Artifacts preserve project grouping. -- Sharing one logical Source across rags makes deleting a rag affect others; share only physical snapshot bytes if desired. -- Storing chunks in Sources violates immutable evidence; one Artifact per chunk obscures whole-document revision semantics. -- Whole-document JSON arrays simplify serialization but make retrieval/detail reads unnecessarily large. -- Separate rag runtime, publication generations and general job tables support advanced features but are unnecessary for atomic revision/index commits. -- Direct SQL deletion of a chunk breaks old revision counts, digests and citations; revision replacement preserves evidence. -- A live fallback to main-path embedding settings can silently change vector space; plugin-owned resolved configuration avoids it. +- Multiple rag Artifacts preserve project-level Scopes without coupling collections to authorization. +- Source journals persist accepted operations without a new mutable task table; in-memory-only commands lose work on restart. +- Request Sources preserve intent; exact successful edit Sources preserve results. Reusing the latter before success misstates provenance. +- Source lifecycle columns express generic deletion while payloads remain immutable; a document-only state sidecar duplicates this responsibility. +- Whole-document manifests plus chunk rows avoid giant content JSON and per-chunk Artifact identities. +- Immutable revision replacement preserves old counts/digests/citations; direct chunk deletion does not. +- Separate task/publication systems could provide richer status/cutovers, but are outside the accepted scope. # Prior art Build on [Source plugins](2012-source-plugin-system.md), [Artifact plugins](2175-artifact-plugin-system.md), [Source identity](1400_source_definition_and_observation_model.md), [processing supervision](1515_artifact_processing_supervisor.md), -and [Source/Artifact APIs](1437_source_artifact_rest_api.md). Existing OpenDAL capture already compares path/content hashes; -Artifact head governance and generic fragment indexes provide reuse foundations, not a complete knowledge-base implementation. -Atomic Memory retirement is a useful lifecycle pattern but is not already a Source-to-document cascade contract. +and [Source/Artifact APIs](1437_source_artifact_rest_api.md). Existing OpenDAL hashing, Source cursor CAS, Artifact +head governance, and fragment indexes provide foundations, not a complete knowledge-base implementation. Existing +Atomic Memory retirement is not already a Source-to-document cascade contract. # Unresolved questions -Implementation must fix precise capability signatures, supported image formats/model versions, resource limits, -backend migrations/transaction behavior, and defaults validated against actual embedding token limits. The three-table -baseline must be verified rather than expanded preemptively. Any core schema change needs a demonstrated gap and review. - -Permanent erasure, restoration, retention/GC, renamed-file identity, complete batch history, independent per-rag -embedding/rebuilds and full edited-Markdown export need separate contracts. Overlapping chunks cannot simply be -concatenated into an accurate edited document. +Fix exact Source/capability signatures, supported image/model versions, limits/chunker defaults, bounded retry error +classification, and backend migration/index transaction behavior during implementation. Additional query projections +must be justified by measured costs. Durable per-request outcomes, restore/erasure/GC, rename identity, per-rag vector +spaces, and full edited-Markdown export need separate contracts; overlapping chunks cannot simply reconstruct a full edit. # Future possibilities -Additional OpenDAL providers, parsers, richer chunkers, rerankers and bounded agentic retrieval may extend the component -boundaries. Measured storage pressure may justify shared immutable chunk bodies. None is required for first-phase -ownership, duplicate detection, atomic commits or exact evidence. +Extend OpenDAL providers, parsers, chunkers, rerankers, and bounded agentic retrieval through component boundaries. +Measure before adding shared immutable chunk bodies, richer task state, or collection-scale projections. None is +required for the first phase's ownership, recoverable requests, versioned content, and exact evidence. diff --git a/docs/zh/rfcs/2570-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md index d71022a6ed..59c55a1991 100644 --- a/docs/zh/rfcs/2570-rag-knowledge-base.md +++ b/docs/zh/rfcs/2570-rag-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570:基于 rag Artifact 的文档知识库" -description: "复用 Source、Artifact 和后台处理设施,通过 OpenDAL 接入文档、简单 Markdown 切块和插件独立检索配置构建知识库。" +description: "复用 Source journal、后台 Worker 与 Source 生命周期元数据,实现 OpenDAL 接入、文档 chunk 版本和知识库检索。" --- - Proposal Name: `rag_knowledge_base` @@ -11,371 +11,385 @@ description: "复用 Source、Artifact 和后台处理设施,通过 OpenDAL # 概述 -通过文档 Source 插件和 document、rag 两个 Artifact family 提供知识库。一个 Scope 可有多个用户创建的 rag, -每个文档 Source 和 document 唯一归属一个 rag。OpenDAL 采集本地文件,Markdown 与图片 OCR 共用简单 Markdown 切块策略, -复用 Artifact Worker,在内容和索引准备好后一起提交 document revision。复用核心元数据表结构、CRUD、监督和通用索引存储, -仅增加文档明细与目标记录。本文是建议契约,不表示功能已发布。 +通过 Source 插件和 document、rag 两个 Artifact family 提供文档知识库。一个 Scope 可有多个用户创建的 rag, +每个文档 Source 和整篇 document Artifact 唯一归属一个 rag。OpenDAL 采集不可变原文,Markdown 与图片 OCR 共用简单切块。 +异步操作请求保存为不可变 Source,通过现有 journal、cursor 和 Worker 消费;document revision、chunks、lineage、索引与消费游标原子提交。 + +新增一张文档 chunk 表,并给 pc_sources 增加通用软删除字段。复用 Artifact 存储和后台处理表,不另建导入/任务/状态平台。 +展示内容是否可用,不提供持久逐文件执行状态。本文是建议契约,不表示功能已发布。 # 动机 -业务描述和 SOP 需要完整文档的片段检索、精确出处、显式更新和可预测的删除行为。记忆提取无法保留每个片段。 -首期应覆盖这条流程,不另建任务平台、逐 rag 索引代次系统或重复 Artifact 主表。 +业务描述和 SOP 需要整篇文档的片段检索、精确出处、显式更新和可预测的删除。记忆提取无法保留每个片段。 +首期应依托现有 Source/Artifact 基础设施覆盖该流程,同时明确失败语义。 -Source 快照和历史 document revision 是证据,知识库检索是派生投影,与 Memory 检索数据和默认配置隔离。 -复用基础设施,但不能把现有插件声明视为已具备定向导入、分行 chunk 存储和删除校验的全部能力。 +原文快照、已接受的操作请求和成功 Artifact revision 各有职责,不能把可变任务状态写入 Source payload。 +检索从已提交 chunks 派生,与 Memory 索引及配置隔离。复用仍需实际适配 family、读取、投影和 Worker。 # 使用层说明 -1. 在已有 Scope 中通过通用 Artifact 创建 rag。 -2. 选择 rag 和本地目录/文件,客户端使用配置好的本地 OpenDAL Source 插件;用户无需提供 Source ID、namespace、hash 或 document ID。 -3. 查看逐文件最新处理状态,输入已接受不代表内容可检索。 -4. 检索指定 rag 的文档,或显式选择多个已授权 rag。 -5. 修改文件后再次导入:相同且已处理成功的输入跳过,内容变化生成新 Source 和同一 document 的新 revision。 -6. 编辑或删除 chunk 都生成新 document revision,旧 revision 及其 chunk 内容保持完整。 +1. 在现有 Scope 中通过通用 Artifact 创建空 rag。 +2. 使用配置好的 OpenDAL Source 插件,选择 rag 与本地目录/文件。 +3. 查看“已生成/有更新待生成/尚未生成”;没有结果不代表已经失败。 +4. 检索明确选择且已授权的 rag,更新失败时继续使用原提交内容。 +5. 导入变更文件或显式重新解析,从固定原文整篇生成新 revision。 +6. 异步编辑/移除 chunk;先接受请求,成功时提交新 revision,保留历史。 -Scope 仍是授权边界。Source/document 独占归属 rag,不跨库共享逻辑身份。同文件导入两个 rag 会产生不同 Source/document, -底层快照可按实际需要去重。首期支持 Markdown 和独立导入的文字图片,OCR 使用 RapidOCR + ONNX Runtime。 -Markdown 内图片仅保留引用,不抓取、不自动 OCR。SQLite、SeekDB、OceanBase 均须支持完整流程,一个部署选择一种持久化后端。 +用户无需提供文件 hash、namespace 或 document ID。Scope 保持授权边界,同文件导入两个 rag 产生不同逻辑 Source/document, +可选复用物理快照字节。首期支持 Markdown 和独立导入的文字图片,OCR 使用 RapidOCR + ONNX Runtime。 +Markdown 内图片只保留引用,不抓取或 OCR。SQLite、SeekDB、OceanBase 均支持完整流程,一个部署选择一种后端。 -PDF、Office、普通 TXT 导入、语义/LLM 切块、复杂版面/表格重建、定时目录同步、每 rag 独立 embedding 空间、 -单库独立无停机索引切换、完整管理界面和大规模语料性能门槛不属于首期。后续界面使用逐文件状态契约。 +首期不包括 PDF/Office、独立 TXT 导入、语义/LLM 切块、复杂布局恢复、定时目录同步、逐 rag embedding 空间、 +无停机索引切换、任务管理 UI、逐文件持久失败详情、恢复/永久擦除或大规模性能验收。 -# 技术说明 +# 参考层说明 ## 1. 归属与插件配置 ```text Scope - +-- rag K1 -- 拥有 --> 原始 Sources -- 派生 --> document revisions -- chunks - +-- rag K2 -- 拥有 --> 独立 Sources/documents,即使本地文件相同 - -Source 插件:OpenDAL 采集与不可变快照读取 -Document 插件:Markdown / OCR -> Markdown -> chunks、内容版本和溯源 -rag 插件:集合管理、检索策略和索引适配 -共享设施:Source/Artifact API、Supervisor/Worker、事务、数据库/搜索适配 + rag R1 + 原文 Source S1 -> 操作 Source Q1(import)-> document D@1 -> chunks + 操作 Source Q2(edit D@1)-> document D@2 + 成功编辑证据 E2 + 原文 Source S2 -> 操作 Source Q3(reparse)-> document D@3 + rag R2 + 独立的原文 Source、请求和 document + +Source 插件:OpenDAL 采集、快照访问、原文与受信操作 Source 类型 +Document 插件:Markdown/OCR、chunks、revision 写入、操作消费和溯源 +rag 插件:集合配置、检索策略和 chunk 索引适配 +共享设施:Source/Artifact API、Supervisor/Worker、cursor、事务、数据库/模型适配器 ``` -rag 是配置和集合身份,不是消费 Source 生成的结果,可以为空。名称/配置使用 Artifact revision,删除使用现有 head 治理状态。 -不另设 rag 运行状态表或运行状态 API。解析进度属于导入文件,不生成 rag 配置 revision。 - -document 代表整篇文档,稳定身份范围为 `(scope, rag, collection, relative_path)`,chunks 是 revision 内部明细。 -collection 由系统根据注册的存储 binding/instance 和规范化根目录生成,不使用每次变化的扫描 ID。 -Source payload 保存不可变的所属 rag、原路径、相对路径、媒体类型、内容摘要和受管理快照引用。任务固定处理配置快照, -可变状态和解析结果不写回 Source。专用 Source 仅供 document 链路直接消费,在选择、执行、提交时都校验。 +三个逻辑插件可放在同一集成包,应用服务负责协调,不新增第四个插件。Rag 可先于 Source 存在,配置使用 Artifact revision, +删除使用 head 治理,不设 rag 运行状态表。归属显式保存在不可变 Source payload 和 document manifest,不从 tags 或证据 lineage 推断。 +每个原文、请求和 document 只属于一个 rag。 -三个逻辑插件可在一个安装包中交付。知识库插件包独立管理 embedding/索引配置,与 Memory 等主路径分离。 -显式插件配置优先;未指定时,可在安装时用主路径的兼容值初始化并保存解析后的配置快照。保存凭据引用,不把密钥复制进 Artifact。 -之后主路径配置改变,不静默改变插件 profile。配置缺失或不兼容则拒绝启用。 -Parser/chunker 可按 rag 配置,首期 embedding/索引为插件级配置,在各 Scope 的 document family 内共用。 +插件独立持有 embedding/索引配置。显式配置优先;安装时可从主路径初始化兼容的缺省项,并固定解析后的 profile 和凭据引用。 +不把密钥写入 Artifact,也不自动跟随之后的主路径配置变化。Parser/OCR/chunker 可按 rag 配置;首期 embedding/索引 profile +为插件级,在同一 Scope 的 document family 共用。按 family、索引定义和向量空间隔离,模型/维度变化走现有 family 重建机制。 -可以复用模型调用和 SQL 适配代码,但按 family、索引定义、向量空间/profile 身份隔离,查询不隐式混入 Memory 数据。 -插件模型/维度变化沿用现有 family 重建机制及其可用性限制,不新增逐 rag 发布协议。 +文档原文只允许 document 管线直接消费,操作请求只允许其处理器执行。在选择、执行和提交环节校验资格;仅注册新 Source 类型 +并不能阻止已有通用消费者使用它。请求不作为普通生成输入或检索文本。 -## 2. OpenDAL 导入与重复判断 +## 2. OpenDAL 导入、身份与去重 -通过现有 OpenDAL/opendalfs 集成列举和读取本地文件。插件 instance 必须运行在所选路径实际存在的机器上, -远端 Server 不能将客户端本地路径当作自己的文件。相对路径在配置根目录下解析,拒绝越界,路径规范化和符号链接策略保持稳定。 -接受 Source 前将原始 Markdown 字节/图片保存成受管理不可变快照。对实际保存的字节计算 hash,不能对第一次读取算 hash、 -再处理已经变化的第二次读取。读取失败或检测到采集不稳定时允许重试。 +OpenDAL/opendalfs 负责本地列举/读取和受管目录中的不可变快照。插件实例必须能访问选定路径。固定根目录、相对路径和 +符号链接规范化策略,拒绝越界。先保存快照,再接受 Source,对保存字节计算 hash 并解析该快照,不能解析随后变化的文件。 +mtime/size 仅是提示,不证明内容相同。复用已有 Source 时保留首次 canonical 采集信息。 ```text file_key = (scope_id, rag_id, collection_id, normalized_relative_path) -content_digest = SHA256(采集到的原始字节) -source_key = hash(Source schema 版本, file_key, content_digest) -processing_key = hash(content_digest, parser/OCR/model 版本及配置, - Markdown 规范化版本, chunker 版本及参数) -index_key = hash(完整 embedding 输入, 插件 profile 和投影版本) +document_id = stable_hash(identity_version, file_key) +content_digest = SHA256(captured raw bytes) +source_key = stable_hash(source_schema_version, file_key, content_digest) +processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) +index_key = hash(complete embedding inputs, plugin profile and projection versions) ``` -mtime/大小可辅助选择工作,但不能证明内容相同。hash 碰撞时比较完整身份,不能截断路径或仅按摘要合并文档。 -用户可见 Source ID 由框架结合插件的确定性身份规则生成。复用已有不可变 Source 时保留第一次 canonical 采集元数据, -不覆写 mtime 或注释。 +Collection 由已注册存储实例/绑定和规范化根目录派生,不使用 scan token。Hash 命中还需核对完整身份,不截断路径或仅按摘要合并。 +原文 payload 包含 owner rag、文件身份、原始路径、document ID、media type、摘要和快照引用。Artifact 尚未存在时即可得到相同的 +确定性 document ID,无需预留表行。 -| 观察结果 | 处理规则 | +| 情况 | 行为 | | --- | --- | -| 同文件/内容/处理指纹,已有成功结果 | 复用 Source 和 document,不生成新 revision;另查索引是否就绪 | -| 相同目标正在等待/运行 | 合并到现有目标,不重复解析 | -| 输入相同,但上次处理失败 | 保留固定 Source,允许有界重试;采集 checkpoint 不等于处理成功 | -| 同路径,字节变化 | 新增 Source,生成同一 document 的新 revision | -| 字节相同,parser/OCR/chunker 变化 | 复用 Source,显式重处理并生成新 revision | -| 仅 embedding/索引 profile 变化 | 使用已提交 chunks 重建,不再次 OCR | -| 路径或 rag 不同,字节相同 | 不同逻辑文档和 Source,仅可复用物理快照 | -| 遇到已删除身份 | 不自动恢复;首期无恢复接口,需显式采用新身份 | +| 同文件/内容/处理 profile,已有可用成功结果 | 复用 Source/document,跳过解析,单独检查索引就绪情况 | +| 存在尚未消费的等价请求 | 扫描未消费 journal 时可合并;并发重复 import 在执行时再次检查成功结果 | +| 同输入但无成功结果 | 显式重试可创建新请求;采集 checkpoint 不等于处理成功 | +| 同路径字节变化 | 新原文 Source,相同 document ID,成功后整篇新 revision | +| Parser/OCR/chunker 变化 | 复用原文 Source,显式请求重处理 | +| 仅 embedding/索引变化 | 从已提交 chunks 重建,不重复 OCR | +| 同内容不同路径/rag | 不同逻辑 Source/document,可选复用物理快照 | +| 人工编辑/移除后原文未变 | 保留人工版本,不把人工正文 hash 当原文 hash 比较 | +| 重新解析人工修改过的文档 | 必须明确 manual_edits_policy=discard,否则保留当前内容并拒绝冲突 | + +文件回到旧字节可能复用较早的 Source,因此期望输入依据最新接受的 import/reprocess 请求,而不是最大原文 Source journal position。 +找到 Source 不证明当前 document 已匹配。首期改名视为新身份,目录文件消失不自动删除。已删除 Source 身份与 retired document +不能被静默恢复。 + +复用 Source collect 的发现/add/status/control。客户端生成的 scan_token 放在插件 input 中标识一次显式扫描;重试相同输入 +复用采集目标。再次扫描使用新 token,但文件身份不变。每 token 扫描一次,不暗示定时同步或重复 add 会启动 stopped target。 +采集状态仅描述接入;扫描还需检查成功 document 结果,不能只看 checkpoint。 + +## 3. Markdown 规范化与切块 -文件恢复到曾经出现过的字节时,也要比较当前目标/结果;找到旧 Source 不代表当前 document 已是该内容。 -首期改名按新路径处理,文件消失不隐含删除。相同文件重扫不能覆盖人工编辑/移除。 -含人工修改的文档遇到输入变化或显式重处理时,要求 manual_edits_policy=discard,否则保留旧提交版本并报告可操作的冲突。 -原始输入 Source 可以已经采集,但内容处理仍保持阻塞。 +```text +Markdown 字节 -> markdown-it-py 结构/字节映射 -----+ + +-> 规则切块 +图片 -> RapidOCR 文字/区域 -> 规范化 Markdown -----+ +``` -目录导入复用 Source collect 能力发现和现有 add/status/control 操作。客户端在插件 input 中生成 scan_token, -标识一次显式扫描目标。同 input 重试 add 复用目标;用户再次导入使用新 token,但 collection/file 身份不变。 -插件每 token 只扫描一次,并继续等待后续目标,不定时重扫。现有 Source status 表示采集状态,不是完整文档处理或批次历史。 -新扫描必须同时检查文档处理状态和采集 checkpoint,避免“采集未变”掩盖下游失败。 +OCR 保留实际文字、顺序、置信度和原图区域,包括预处理坐标变换。规范化只转义 Markdown 语法、组织行/段落,不虚构标题、 +不做 LLM 校正或复杂表格恢复。规范化文本跨度映射回 OCR 行和原图区域,并声明 locator 精度。派生 Markdown 不替换图片 Source。 -## 3. Markdown 规范化与简单切块 +按标题、段落、列表和代码块组织,短块合并至 max_chunk_chars,过长块按句子/长度拆分,可用 overlap_chars 保留上下文。 +保留标题路径、语言和续块标记。Overlap 必须小于最大长度,1200/100 仅为待验证示例;调用 embedding 前校验包含标题/前缀的 +完整输入 token 预算,不能静默截断。 -两种输入形成统一 Markdown 视图: +明确校验格式、UTF-8、图片解码/像素上限、OCR 模型、超时和无文字结果,固定并验证真实 RapidOCR、ONNX 和模型版本。 +OCR 无文字不算成功空文档;显式移除最后一个 chunk 则允许。无需独立章节树、解析节点表或完整 Markdown 缓存。 +Chunk metadata 保存有界出处映射,canonical chunks 不存向量,Artifact manifest 不存全文。 -```text -Markdown 字节 -> markdown-it-py 结构/原文字节映射 ---+ - +-> 规则切块 -图片 -> RapidOCR -> 文字行/区域 -> 规范化 Markdown --+ -``` +## 4. 持久化:一张明细表与 Source 生命周期字段 -OCR 保留真实文字、顺序、置信度和原图区域,考虑预处理坐标变换。Markdown 转换只做语法转义、文字行/段落组织, -不猜标题、不用 LLM 修正文案、不重建复杂表格。保留规范化文字跨度到 OCR 行和原图区域的映射。 -规范化 Markdown 是派生内容,不能替代图片 Source;定位必须说明真实精度。 +不新增 pc_document_imports、pc_document_source_states。Source payload 保存不可变身份/请求,Artifact 保存成功 revision, +现有处理表协调消费。不能用 rag content、Scope settings、checkpoint 或 cursor 中的无界字典替代这些表。 -按标题、段落、列表和代码块处理,合并短块直到接近 max_chunk_chars,超长块再按句子/长度拆开, -必要时在拆分边界保留 overlap_chars,并校验 overlap 小于最大长度。保留标题路径、顺序和续块标记,不建设独立章节树系统。 -Embedding 前还要检查真实模型 token 预算,包括标题/前缀上下文,不静默截断。改变边界的切块配置变化需要版本化。 +| 复用设施 | 职责及结构变化 | +| --- | --- | +| pc_sources | 原文、操作请求、成功编辑证据;增加下述通用生命周期字段 | +| Source journal/heads、connector checkpoints | 接受顺序和采集进度,结构不变 | +| pc_source_cursors | document binding 的连续扫描位置和 CAS generation,结构不变 | +| Processing intents、leases、binding state | Scope/binding 唤醒、调用代次和执行栅栏;结构不变,不是逐文件任务表 | +| pc_artifacts、pc_artifact_heads | rag 配置、document manifest、当前 revision 和 retirement/治理,结构不变 | +| Source/Artifact lineage、locators、tags | 原始输入、请求、base revision 和成功编辑证据,沿用结构 | +| Artifact search states/coverage/changes/text/vectors | 当前版本片段索引和构建协调,复用设施并增加 chunk 投影适配 | -媒体校验、非法 UTF-8、损坏/不支持图片、无识别文字、模型缺失、像素超限和超时分别处理,固定并验证真实 RapidOCR、ONNX 和模型版本。 -规范化 Markdown 可以在处理期间计算,首期不要求独立解析缓存。Chunks 保存有效文字和有界来源映射,不保存向量。 -Artifact manifest 有界,不嵌入全部 chunks。 +给 pc_sources 增加: -## 4. 持久化:核心表结构不变,三张支撑表 +| 字段 | 类型/默认值 | 语义 | +| --- | --- | --- | +| lifecycle_state | 短字符串、NOT NULL、默认 active | active/deleted,首期单向转换 | +| deleted_at | 可空 UTC 时间 | 首次删除时间,重复删除不刷新 | -本方案不修改现有核心元数据表定义。新 family 记录、声明和索引沿用既有 schema,这是迁移约束,不代表无需修改处理代码。 +已有 Source 回填 active,payload、身份和 journal position 保持不可变,生命周期元数据不参与内容 hash。 +通过行锁/条件更新和统一锁定顺序与 document 提交互斥,首期不额外增加 Source 删除代次列。 +适配 add/get/list、证据/生成访问和 family 读取;重复 add 命中已删身份时不能返回可用内容或恢复。 +内部迁移/级联扫描可包含已删行,公共读取不能绕过。三个后端验证加法迁移,不能把 Artifact retirement 当作已有 Source 软删除能力。 -| 复用设施 | 用途与必要代码适配 | -| --- | --- | -| `pc_sources`、Source journal、connector checkpoints | 不可变输入、采集身份和采集进度 | -| `pc_artifacts`、`pc_artifact_heads` | rag 配置、document revision manifest、active/retired 状态和治理 CAS | -| `pc_artifact_lineage_sources`、locators、Artifact lineage、tags | 原始输入、系统编辑 Source、base revision 和标签,不表示可变成员关系 | -| `pc_artifact_processing_intents`、租约、binding 状态 | 持久唤醒、显式请求代次、执行资格和注册栅栏 | -| `pc_artifact_search_states`、coverage、changes | 现有 Scope/family 构建协调及当前版本索引维护 | -| `pc_artifact_search_text`、vectors、向量空间/索引定义 | 片段级检索投影,family=document、fragment_id=chunk_id | +唯一新增领域表为 pc_document_chunks: -不新增 pc_rag_runtime、逐 rag generation/publication、通用 jobs/receipts 系统、独立 nodes/目录主表。 -不把状态塞进无关 Scope settings,也不改 Source payload 模拟可变元数据。文档归属必须显式,不能从标签或证据 lineage 推测。 +| 约束/字段 | 设计 | +| --- | --- | +| 主键 | (scope_id, document_id, revision, chunk_id) | +| 唯一顺序 | (scope_id, document_id, revision, ordinal) | +| 内容 | text、content_digest | +| 结构 | 标题路径、续块/重叠元数据 | +| 溯源 | 规范化跨度、原文字节/图片定位、origin/verbatim、base/edit 引用 | -以下三张支撑表是建议实现基线。使用 UTC 时间、字节精确身份比较、有界 JSON 和满足各后端限制的键长度。 -迁移必须核实三个后端的实际布局;只有唯一性和恢复语义相同时才能用既有存储替代。 +使用后端安全键长与有界元数据。每个 revision 是完整不可变 chunk 快照:100 块移除一块生成新 manifest 和 99 行,保留旧的 100 行。 +Manifest 保存 owner rag、文件身份、root SourceRef、schema/处理指纹、chunk 数量/摘要、人工修改标记和 applied_request_ref。 +历史读取使用精确 revision,而非当前 head。 -| 表 | 主键/唯一键 | 最小字段与职责 | -| --- | --- | --- | -| `pc_document_imports` | PK `(scope_id, document_id)`;UQ `(scope_id, rag_id, collection_id, path_hash)` | 完整相对路径、binding name、当前/目标 SourceRef 与摘要、处理/配置快照和指纹、目标代次、operation(import/reprocess/edit)、有界待处理编辑、request ID/digest、state/stage、attempt、重试时间、lease token/expiry、结果 revision 和 error;合并身份预留、成员关系和逐文件最新工作 | -| `pc_document_chunks` | PK `(scope_id, document_id, revision, chunk_id)`;UQ `(scope_id, document_id, revision, ordinal)` | text、内容摘要、标题路径、续块/重叠元数据、规范化跨度和原文字节/图片定位、origin、编辑/base 引用;完整不可变 revision 快照 | -| `pc_document_source_states` | PK `(scope_id, source_type, source_id)` | 不可变 owner rag_id、document/文件身份、state=active/deleted、删除代次/时间;原始 Source 及其系统编辑 Source 的独立可变生命周期 | +首期成员和可用性查询可以按 Scope/类型分页扫描解码 payload,再按确定性 document ID 精确读 Artifact。不能假设 canonical payload +已具备可查询的 JSON owner/path 索引。过滤分页按扫描位置继续,不能丢失后续匹配项;写入/读取验证归属和完整身份。 +扫描有成本,本方案不承诺大规模性能。额外投影需有测量依据,不能隐式重新引入任务表。 -解析前预留 document ID,但不要求 Artifact head 已存在。提交后明细引用同 Scope 的 family=document,每个 Source owner -匹配预留记录和不可变 payload。Manifest 保存所属 rag、root SourceRef、schema/处理指纹、chunk 数量/摘要和人工修改标记。 -100 块的 revision 保存一条 manifest 和 100 行明细;移除一块生成新 manifest 和 99 行,不改原来的 100 行。 -未变行可高效复制,但不完整快照不能可见。历史版本按精确引用读取,不能用当前 head 解释历史。 +## 5. 操作 Source、Worker 与事务边界 -按 `(scope, rag, document_id)` 索引导入记录,按 binding/状态/重试时间查待办,按 revision/ordinal 读 chunks, -按 `(scope, rag, document_id)` 索引 Source 状态支持删除传播。核实既有反向 lineage 查询路径以支持原始 Source 撤销。 -Hash 键同时保留完整原始身份用于比较。Source 行归属不随状态/进度改变。 -导入表保留最新目标和结果,不记录无界批次或命令历史。Source 接受前的错误归采集诊断;完整持久批次历史需另行明确扩展范围, -不能用元数据行里的无界 JSON 数组实现。 +受信应用服务创建专用操作 Source 类型,示意名 document_operation,原文示意名 document_file;它们是插件注册,不是新存储表。 +请求保存 owner rag、document ID、operation、root SourceRef、固定处理配置/指纹、request ID、base revision,以及有界编辑/discard 参数。 +首次导入可无 base,编辑必须固定已有 base。Payload 不包含可变 state、attempt、error 或未来输出 revision,普通用户 metadata 不能伪造命令。 -## 5. 复用 Worker,内容与索引原子提交 +Import/reprocess 从固定原文整篇生成;edit 支持 replace_text、remove。现有 ContentSourceInternal 表示成功 artifact_create/artifact_replace, +且绑定精确 revision,不能表示未执行命令。保留其成功语义,待执行请求使用专用类型。 -应用服务协调三个插件,不是新增插件或服务。Source 接受/复用、生命周期初始化、document 目标预留/更新和 -processing_intents.request() 同事务提交,唤醒通知丢失后也能从持久目标恢复。 -仅提交 Source 的入口也必须调用同一接受能力,不能绕过目标验证。 +原文接受/复用、请求插入和 document binding 的 processing_intents.request() 同事务完成。只有新接受的请求发布新工作。 +需显式适配 Source/binding 通知,当前 SourceRepository 不会自动发现本方案的 processor。 -Supervisor 保持 Scope/binding 调度,document processor 选择导入表中的待办,不向所有 rag 广播 Source。 -已有 Source 的重试/重处理使用显式请求,不伪造正 source_through,也不为纯目标工作推进 Source cursor。 +请求身份在 Scope/rag/document/operation 和客户端 request_id 范围确定性生成。Canonical payload 相同的重放返回已接受请求, +相同身份但不同内容冲突。重放已消费请求不再次执行;显式重试使用新 request ID,可复用同一原文 Source。 +只增加调用计数不能重新执行已被 cursor 越过的输入。 ```text -pending -> running -> succeeded - +--> retry_wait -> pending - +--> failed / blocked -新目标 -> 目标代次递增,旧执行结果过期 -rag/document/Source 删除 -> 受影响目标 cancelled,禁止后续提交 +请求 Source + processing intent 原子接受 + | +现有 Worker 顺序扫描 document binding 的 journal 窗口 + | +事务外准备 chunks/embedding + | +document + chunks + lineage + 索引 + cursor 原子提交 ``` -每个逻辑文档只处理一个当前目标。相同待办合并,新的文件版本可以取代旧解析;人工编辑要求不存在冲突的待处理变更。 -持久保存操作、固定输入/配置、base revision 和最新请求 token,使重启后能重试相同工作。 -当前 token/digest 重放返回当前状态,同 token 不同内容冲突;过期 token 版本不能重新创建工作,不承诺无限期的历史回执重放。 +同 Scope/document binding 内顺序处理,采用有界窗口和既有栅栏/cursor CAS。不相关 Source 只推进连续扫描边界。 +不提供逐文件队列或“最新请求自动取消旧请求”的保证。请求固定 base;前序操作改变 head 时,后续请求可能冲突,不能静默换 base。 +用户刷新后提交新请求。执行期间接受的新 Source 不修改运行中的请求。Scope invocation 依照既有 ScopeInvocation 契约确认, +处理部分工作不能把整个窗口标成 clean。 + +Cursor 表示已消费,包含跳过,不表示成功。成功 revision 通过 applied_request_ref 和 lineage 关联请求;没有持久逐请求失败回执。 + +| 结果 | Cursor 与恢复 | +| --- | --- | +| 单输入解析/OCR/配置错误或 base 冲突 | 记录脱敏标识/错误,在执行栅栏保护下越过该请求,保留旧内容,继续其他输入 | +| 请求局部短暂错误 | 可在进程内有限重试,耗尽后同样记录并跳过,不持久保存 attempt | +| 数据库故障、索引重建或系统性模型不可用 | 不推进该请求,复用 Supervisor 退避/恢复,报告 binding 级不可用 | +| 提交前进程退出 | Cursor 未推进,恢复后重执行固定请求 | +| 成功提交后进程退出 | 内容与 cursor 已提交,不重复创建 revision | +| 输出失败日志后、跳过事务前退出 | 可能重新执行,允许重复诊断 | + +日志遵循现有可观测性契约,不包含正文、凭据或敏感路径,也不是恢复依赖。已消费失败请求需显式新请求重试。 +运行时任务状态或请求超时不能证明永久失败。 | 边界 | 工作 | | --- | --- | -| 事务外 | OpenDAL 快照采集、解析/OCR、Markdown/chunk 构造、embedding 和索引投影准备 | -| 接受事务 | 校验归属/生命周期和前置条件,接受/复用 Source 与目标状态,提交现有 processing intent | -| 内容事务 | 重验目标代次、base head、所属 rag/Source 生命周期、插件 profile/build 和 Worker 栅栏;一起提交 manifest、完整 chunks、lineage、必要系统编辑 Source、head、索引和目标成功状态 | -| 删除事务 | retire 父 Artifact 或标记 Source 已删,使目标失效;利用现有 invocation 和目标行持久化可恢复的传播工作 | +| 事务外 | 快照采集、解析/OCR、完整 chunk 快照、embedding 和索引投影准备 | +| 接受事务 | 权限、归属/生命周期/base 校验,Source/请求接受,processing intent | +| 成功内容事务 | 重验 Worker/cursor/base/owner/root/索引栅栏;提交 manifest、chunks、lineage、必要成功编辑证据、head、索引及 cursor | +| 失败跳过事务 | 重验执行/cursor 栅栏并推进连续边界,不写 document 或成功编辑证据 | +| 删除事务 | 标记 Source 生命周期或 retire Artifact head,由父/root 校验阻止并发发布 | + +模型调用和 DDL 在内容事务外。Chunk 投影从 chunks 准备,不从 manifest 中假设存在全文;提交验证快照和投影指纹。 +新内容与索引一起可见,更新失败保留旧 head/索引。Family 重建时延后 document 提交,不走通用“仅提交内容”路径。 +重建读取已提交 chunks,不重复 OCR;明确不可用,不回退 Memory/纯全文,也不保证零停机。 +三个后端需验证实际事务,包括 SQLite 写锁;ANN 过滤限制需通过限定集合精确检索或明确能力错误处理。 -模型调用和 DDL 不在内容事务里执行。Chunk 投影适配器从完整 chunk 快照准备索引,不能假设有界 manifest 包含全文。 -提交时同时校验快照和投影指纹,现有通用 JSON 字段投影不经适配并不满足要求。 +## 6. 编辑、chunk 移除与删除 -正常更新失败保留原提交 head 和索引,不生成“已可读但尚未索引”的新 revision。历史内容可精确读取,检索使用当前索引 revision。 -共享 document family 索引重建或不可用时,延后新文档提交并明确报告不可用;不能静默走通用框架“重建时仅提交内容”的路径, -不能回退 Memory 检索,也不承诺无停机切换。重建读取已提交 chunks,不重新 OCR。 -SQLite、SeekDB、OceanBase 都需通过真实适配验证事务/读取;原生 ANN 无法保证过滤语义时,使用限定集合精确检索或明确报能力不足。 +编辑 If-Match 在接受和提交时分别校验,成功生成完整新快照。未变 chunk 保留逻辑 ID,重切块分配新 ID;引用始终带 revision。 +移除最后一块后保留可读零块 manifest,当前索引没有片段;任何移除都不物理删除历史 chunk 行。 -## 6. 编辑、chunk 移除与软删除 +成功时创建系统 Content Source,role=lineage_only、operation=artifact_replace,绑定真实新 revision,记录请求/base/root 修改依据。 +显式保留原始 Source 依赖。编辑文字标记 origin=manual_edit、verbatim=false,原图坐标只表示修改依据,不证明新文字逐字存在。 +Remove 同样算人工修改,重新解析需明确丢弃授权。完整 embedding 输入未变可复用计算,但索引映射仍需指向新当前 revision。 + +| 删除操作 | 行为 | +| --- | --- | +| 原文 Source | Source lifecycle 标记 deleted,retire 当前仍以它为 root 的 document,并撤销相关历史读取;其他 root 完整重解析的版本保留 | +| Document | Retire head,阻断所有 revision/chunks 和后续命令,原文 Source 保持 active | +| rag | Retire head,立即阻断所属内容,再可恢复地标记全部所属 Source(含请求/编辑证据)和 document head | +| Chunk | 提交不包含该块的新 revision,保留历史 | -编辑命令支持已有 chunk 的 replace_text 和 remove,使用 document If-Match。Worker 构造完整新 revision,重新校验数量/顺序/摘要, -准备索引后原子提交。允许删除最后一块:有效内容为空、索引片段数为零,但保留可读 manifest 和溯源。 -未变 chunks 保留逻辑 ID,重切块生成新 ID;引用始终带 revision。Remove 只影响新快照,不物理删除历史 chunk 行。 +复用 Artifact lifecycle_state=retired 和治理 CAS。原文 payload/快照及历史业务内容保留,不动用户文件,首期无恢复/永久擦除。 +尚无 head 的导入文件通过原文 Source 删除;document DELETE 返回不存在,不虚构占位 Artifact。 +删除待处理替代 Source 不 retire 仍依赖另一 root 的旧提交版本。 -成功提交时创建 role=lineage_only、operation=artifact_replace 的系统 Content Source,记录精确新 revision、base revision 和编辑/移除命令。 -该 Source 用于修改溯源,不进入普通解析。显式保留原始文档 Source 依赖,不能假设通用替换已自动继承。 -修改文字标记 origin=manual_edit、verbatim=false,原图位置只是修改依据,不表示新文字逐字存在于图片。 -移除 chunk 也算人工修改,重解析不能静默覆盖。完整实际 embedding 输入/profile 未变时可复用计算,但仍更新新 revision 的索引映射。 +检索和通用精确/历史/chunk 读取检查 owner rag、document head 和精确 revision 的 root。历史 base 链接不让完整重解析版本传递依赖旧 root。 +原文读取校验自身状态/owner,单删 document 不隐藏原文;请求/编辑证据读取还需校验目标 document,避免保留的人工正文绕过删除。 +删除请求会阻止尚未消费的执行,不撤销已提交编辑;内容有效性由 root/document/rag 决定,而非事后取消请求。 -| 删除操作 | 状态与影响 | +通用 retirement 可能仍允许精确读取,需增加 family guard。大规模 rag 级联从 retired 父对象和不可变归属重新发现剩余工作, +内部包含已删行,无需 cascade job 表。即使传播未完成,也必须在排名前排除无效对象。 +派生索引沿用替换/移除/重建;保留业务历史不等于保留每个历史索引条目。 + +## 7. 可用性与统一接口 + +| 展示 | 推导依据 | | --- | --- | -| Source | sidecar 标记 deleted,不改 payload;当前输入仍为它的 document retire,相关历史 revision 和编辑 Source 不可读;仅依赖替代 Source 的当前版本保留 | -| Document | Artifact head retire,阻断全部 revision/chunks 和待办;不删除原始 Source | -| rag | head retire,立即阻断全部所属内容,再持久完成所属全部 Source 版本和 document head 的删除/retire 标记,包括尚未处理成功的目标 | -| Chunk | 生成不包含该块的新 document revision,保留历史内容 | - -Retire 复用 lifecycle_state=retired 和 governance CAS,不新增第二套 rag/document 删除标记。 -Source payload 不可变,因此删除放在 sidecar。重复删除幂等。 -仅预留、尚无 head 的 document 在导入行以 document_deleted 原因终止,不为删除而创建空 Artifact;后续扫描不能静默恢复该身份。 -删除待处理替代 Source 只取消其目标,不 retire 依赖另一 Source 的已提交版本。 -较大级联可分批完成:已 retire rag 和持久归属使未完成工作可重新发现,父状态立即阻断读取/提交。 -Source 不跨 rag 共享逻辑归属,因此删库不误删其他库的 Source。保留 OpenDAL 快照和 canonical/历史内容,不删除用户原文件; -首期不提供恢复或永久擦除。 - -检索及通用精确/历史/chunk 读取校验所属 rag、document head 和该 revision 的根 Source。 -历史 base revision 链接不让完整重解析的替代版本传递依赖旧 Source。系统编辑 Source 也检查其 document/rag 目标。 -原始 Source 读取检查自身状态和 owner rag;单删 document 后原始 Source 仍可读,删其 rag 后不可读。 -必须增加 family 读取校验,不能只依赖通用 retirement,因为既有行为可能仍允许精确读取。 - -搜索索引是派生结构,不是历史证据,沿用现有替换/移除/重建维护。软删除保留业务数据,不承诺原样保留每个历史索引条目。 -即使旧索引暂存,排名前也必须排除,包括删除传播恢复期间。不论物理索引是否清理,都必须检查父对象/Source 和提交栅栏。 -已经发送的响应无法收回。 - -## 7. 统一接口契约 - -以下路由为建议复用或扩展,当前 schema 尚未支持全部 family/filter。实现时修改 openapi/powercontext.yaml 并重新生成绑定。 -复用权限、错误封装、Artifact/Source 引用、分页、ETag 和 SDK/MCP 映射。 -不把文档文件塞进目前只接受 built-in content 的通用 create-Source 命令,使用 Source 插件协议。 +| 已生成 | 有可用提交 revision,匹配选定原文/配置,保留有效人工修改 | +| 有更新待生成 | 有可用旧 revision,但期望原文/配置不同;旧内容仍可检索 | +| 尚未生成 | Source 已接受但无可用成功 revision,可能未开始、运行中或失败 | +| 已删除 | Source 或所属 Artifact 生命周期无效,不返回保留正文,普通列表默认排除 | + +期望输入取最新接受的 import/reprocess 请求,无请求时取已接受原文。人工编辑不是原文件不匹配。 +Rag 配置变化影响后续请求,可提示需要重处理,但不自动入队。不展示逐文件阶段、百分比、attempt 或持久错误, +不从采集完成/cursor 推进推断成功;binding 诊断和索引可用性单独处理。 +复用权限、错误、引用、分页、ETag 与 SDK/MCP 操作。必要契约改动写入 openapi/powercontext.yaml 并生成绑定。 +当前通用 create-Source 只接受 built-in content,文档文件使用 Source 插件协议。 约定 `R=/v1/scopes/{s}/artifacts/rag/{r}`,`D=/v1/scopes/{s}/artifacts/document/{d}`。 -| 操作 | 复用或必要扩展 | 语义 | -| --- | --- | --- | -| 创建/配置 rag | 现有 POST `/v1/scopes/{s}/artifacts`、GET/PUT `R`、revisions/tags | family=rag,完整配置替换和既有 If-Match;创建空库不解析 | -| 导入目录/文件 | 现有 POST `/v1/source-management/add`,使用发现的 collect capability 和 instance | 插件 input 携带 owner rag 和本地根目录/文件;Source 回执仍表示采集,不新建 rag import/job 封装 | -| 采集状态/控制 | 现有 source-management status 和 target/instance controls | 不声称 collect add 会重新调度 stopped target,也不把 status 当完整批次历史 | -| Source/document | 现有 Source list/get、Artifact list/get/history | 缺少时增加经过验证的 owner-rag 过滤;document GET 返回有界 manifest,不返回所有 chunks | -| 最新逐文件进度 | 新增 GET `R/processing`,cursor/state 过滤 | 最新目标、阶段、attempt/error、请求代次和已提交 revision,包含无 Artifact 的预留记录 | -| 重试/重处理 | 新增 POST `D/processing`,首次失败无 head 时也可使用预留 document ID | action、expected_target_generation、request_id、可选丢弃策略;202 当前目标回执 | -| 读取 chunks | 新增 GET `D/revisions/{rev}/chunks` | 复用 items/next_cursor,精确 revision 的有效 chunks 和出处 | -| 编辑/移除 chunk | 新增 POST `D/edits` | document If-Match、有界类型化操作和 request_id;202 仅表示待办,原子成功后才生成新 revision | -| 检索 | 现有 POST `/v1/scopes/{s}/artifacts/document/search` | 沿用 query/mode/limit/fusion,要求经过验证的 filters.rag_ids;可选匹配片段不替代完整 Artifact 结果 | -| 软删除 Artifact/Source | 给现有精确 Artifact/Source 资源路径增加 DELETE | family writer/Source 生命周期服务校验归属;Artifact 使用 expected_generation(治理 CAS);document 为 scope.contribute,rag/Source 为 scope.admin | - -rag content 保存标题/摘要和 parser/OCR/chunker 配置或引用,不保存运行进度、成员或主路径 embedding 配置。 -修改配置影响后续接受的目标;已有 document 通过显式重处理更新,并继续保护人工修改。 - -创建示例,沿用通用 Artifact 封装: +| 操作 | 现有路由或必要扩展 | +| --- | --- | +| 创建/配置 rag | 现有 POST `/v1/scopes/{s}/artifacts`、GET/PUT R、revisions/tags,完整替换与既有前置条件 | +| 导入/控制 | 现有 POST `/v1/source-management/add`、collect capability/instance 和 status/target/instance controls | +| 文件与可用结果列表 | 现有 Source list/get、Artifact list/get/history,验证 owner-rag filter,helper 按 document ID 合并;不设 R/processing 任务列表 | +| 显式重解析 | POST D/processing,source_ref、action=reprocess、request_id、可选配置/discard;202 表示请求接受 | +| 编辑/移除 chunk | POST D/edits,当前 If-Match、有界类型化操作和 request ID;202 表示请求接受 | +| 读取 chunks | GET `D/revisions/{rev}/chunks`,精确版本、items/next_cursor | +| 检索 | 现有 POST `/v1/scopes/{s}/artifacts/document/search`,query/mode/limit/fusion,经过验证的 filters.rag_ids | +| 软删除 | 在既有精确 Source/Artifact 路由增加 DELETE;Artifact 治理 expected_generation,Source 单向生命周期 | + +已有 head 的重解析需 If-Match,无 head 时使用确定性 document ID 和 If-None-Match: *。验证 Source 归属/文件身份确实解析到该 ID, +执行时重验 base。不把 Scope invocation generation 作为 document target generation 返回。 +Document 操作复用 scope.contribute,rag/Source 删除复用 scope.admin,读取沿用既有授权。 + +创建 rag: ```json -{"family":"rag","content":{"title":"Operations SOPs","summary":"Runbooks and screenshots","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +{"family":"rag","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} ``` -目录采集示例,capability/instance 名称和参数是部署发现值的示意: +目录采集,capability/instance 为部署发现值示意: ```json {"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} ``` -接受时验证目标 rag 引用;归属固定为 rag ID,处理固定已接受配置。scan_token 不是文档身份,不改变 Source 协议顶层 schema。 -客户端重试扫描沿用 token,明确再次扫描使用新 token。 - -移除 chunk 示例,POST `D/edits` 携带当前 document ETag: +POST D/edits 移除 chunk,携带当前 document ETag: ```json {"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} ``` +202 回执说明持久接受,不表示 pending 状态或未来 revision: + ```json -{"document_id":"doc-1","request_id":"edit-03","target_generation":4,"state":"pending","committed_revision":2} +{"accepted":true,"document_id":"doc-1","request_source":{"source_type":"document_operation","source_id":"request-03"},"current_revision_at_accept":2} ``` -回执不能提前虚构 revision 3。稍后 GET processing 返回成功和新提交版本,或失败且 revision 2 不变。 -文字替换使用 kind=replace_text 并提供 text,不把局部操作伪装成通用 PUT 的完整 content。 -当前 request ID/digest 重放复用目标,冲突或过期请求返回冲突/前置条件错误,不静默再次执行。 +current_revision_at_accept 是观察值,不是输出。通过 revision 的 applied_request_ref 确认成功,没有匹配 revision 不证明失败。 +重新执行需刷新前置条件并使用新 request ID,相同请求重放返回原接受事实,不是新的执行结果。 -同 Scope 检索沿用通用请求: +显式重新解析,已有 document 使用 If-Match,并授权丢弃人工修改: ```json -{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} +{"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} ``` -results 继续返回完整 document Artifact manifest 和 lineage。在搜索项上增加可选类型化 matches,携带有界精确 chunk 命中: -chunk ID、text、locator、origin/verbatim 和片段得分。这是响应投影,不写入 Artifact content。 -limit 仍限制返回 Artifact 数量,每 document 的片段数量另有能力上限。只接受已声明 document filters/options, -不支持的 rerank 明确报能力错误;未知 filter 或未指定 rag 均不能扩大查询范围。 - -跨 Scope 查询由客户端/helper 接受明确的 `(scope, rag)` 目标,先逐个授权,再分组调用同一个现有搜索操作并按排名融合。 -保留 document/chunk 身份和逐目标错误,不比较不兼容原始分数,不把失败当无命中。 -首期不新增独立 /rag/query 协议;HTTP、Python、MCP 使用同一 family 操作,必要时执行有界编排。 - -| 情况 | 响应 | -| --- | --- | -| 缺少/过期 document/配置 ETag | 既有 428/412 前置条件错误 | -| 目标代次/请求冲突、存在待处理编辑或缺少人工修改丢弃策略 | 409 与可操作错误码 | -| 对象或证据已删除 | 授权后 410,错误中不返回保留正文 | -| 格式/配置非法或输入超限 | 422;传输层可用 413 拒绝大请求 | -| 索引/模型不可用或重建中 | 503,不静默降级纯全文或检索其他 family | -| 已接受处理失败 | 最新目标 failed/blocked/retry_wait,Source 接受和处理成功分开 | - -错误继续使用现有结构,例如: +同 Scope 检索选定 rag: ```json -{"error":{"code":"resource_deleted","message":"The requested document is unavailable.","details":null}} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} ``` -## 8. 实现与验收 +搜索结果保留完整有界 document manifest 和 lineage,增加可选类型化 matches 表示有界精确 chunk 命中,携带 revision/chunk ID、 +text、locator、origin/verbatim 和得分。这是响应投影,不写入 Artifact content。Limit 计算文档数,每篇片段另有限额。 +不支持的 filter/rerank 明确拒绝,缺少 rag 选择不能扩大范围。跨 Scope helper 逐个授权明确的 (scope, rag),调用相同分 Scope 搜索, +按排名融合,保留目标错误/身份;不比较不兼容原始分数,不另建 /rag/query 协议。 + +接受阶段沿用 428/412 前置条件、409 payload/discard 冲突、授权后 410 删除、422 校验(传输层可用 413)和 503 服务不可用, +保持 error.code/message/details 错误封装。202 之后的请求局部失败/冲突按日志与消费规则处理,不提供持久错误状态端点。 -复用框架仍需文档 Source 接受 hook、Worker 逐文件选择、chunk 明细投影适配、top-k 前归属过滤、所有读取的生命周期校验,以及 -同事务 family writers。不能因为复用表而把全文塞回 manifest,或声称通用 JSON 投影已经足够。 -不计划修改核心元数据列;若实现发现真实缺口,加法领域迁移和 OpenAPI 扩展仍需评审。 +## 8. 实施与验收 -SQLite、SeekDB、OceanBase 各自通过公开操作验证: +复用仍需 Source 生命周期迁移/读取 guard、受信请求接受、消费者限制、document binding 通知、journal 选择/cursor 事务、 +chunk 投影和 top-k 前归属过滤。不代表框架无需适配,也不代表当前路由已经全部支持。 -- 同 Scope 两个 rag 和另一 Scope 的 rag;同文件导入归属独占,查询不串库。 -- 固定 oceanbase/oceanbase commit 的 Markdown 和真实 OCR fixture,保留图片引用及准确出处。 -- 相同成功跳过、相同失败重试、字节变化生成版本、配置变化重处理、仅 embedding 变化不 OCR。 -- 迟到 Worker/冲突编辑拒绝,持久当前目标支持重启;内容或索引失败不暴露半发布版本。 -- 通过新 revision 移除 chunk,包括最后一块;旧快照完整,当前索引不命中已移除块。 -- Source/document/rag 软删除,重启后继续传播,历史/编辑 Source 读取校验,删除旧 Source 不误删替代版本。 -- 插件由兼容主路径配置初始化但不持续耦合,索引隔离,重建期间明确报告不可用。 -- 核心 schema 兼容、过滤混搜、分页和契约生成;mock 不代替真实后端/OCR 验收。 +SQLite、SeekDB、OceanBase 使用相同公开流程验证: -沿用 #2441 负责归属/导入,#2442 负责处理/内容/索引适配,#2443 负责检索/接口,#2444 负责诊断和三后端验收。 -一个实现分支/PR 可按这四个阶段评审。本 RFC PR 不关闭实施 Issue,不新增 Issue,也不从功能 fixture 推断大规模容量。 +- 多 rag/Scope、文件归属独占、授权选择与不串库。 +- 固定 oceanbase/oceanbase commit 的 Markdown 和真实 OCR fixture,保留准确出处。 +- Source 迁移回填、payload 不变、已删重放拒绝、精确/历史/证据读取校验。 +- 成功去重、失败后新请求重试、配置重解析、仅 embedding 变化重建。 +- 请求/intent 原子接受,重启恢复,内容/cursor 原子提交,相同请求不重执行。 +- 单输入失败推进与系统性故障保留,cursor 推进绝不表示文件成功。 +- 异步 base 冲突/迟到 Worker、失败不生成成功编辑证据、人工修改保护。 +- Chunk 移除包括最后一块,历史完整,当前索引正确。 +- Source/document/rag 删除竞争,可恢复级联,替代 root 独立性。 +- 插件配置独立、索引隔离、重建不可用、分页、契约生成和 SDK/MCP 一致性。 + +Mock 不证明真实后端/OCR 支持。#2441 负责接入/归属/Source 生命周期,#2442 负责处理、请求/chunks/原子写入, +#2443 负责检索/接口,#2444 负责诊断/验收。一个实现分支/PR 可分阶段交付;RFC 不关闭实施 Issue,也不证明大规模容量。 # 缺点 -完整 chunk 快照增加存储与写入,软删除原文/历史保留需要容量监控。共享 document-family 重建可能影响同 Scope 多个 rag 的检索。 -逐文件最新状态比任务中心简单,但不提供完整批次/命令历史。即使核心 schema 不变,插件专用读取/投影/接受适配仍有实际开发量。 -OCR 分发和平台支持需测试。 +操作 Source 增加 journal 行,完整 chunk 快照和软删除保留消耗存储。顺序消费可能等待前序文件;可用性展示没有逐请求持久失败详情, +首期 owner/请求过滤可能扫描 payload。Family 重建可中断多个 rag。这些是首期明确取舍,Source 生命周期、消费者/投影适配仍有实际工作量。 # 设计理由与替代方案 -- 一个知识库一个 Scope 会将集合组织绑定到授权;多个 rag Artifact 保留项目分组。 -- 跨 rag 共享逻辑 Source 会让删库影响其他库,仅在需要时共享物理快照字节。 -- 在 Source 存 chunks 破坏不可变证据,每 chunk 一个 Artifact 则难以表达整篇文档版本。 -- 全文 JSON 数组简化序列化,但会放大检索/明细读取。 -- 独立 rag runtime、发布代次和通用任务表可支撑更复杂能力,但内容/索引原子提交的首期无需这些结构。 -- 直接 SQL 删除 chunk 破坏旧 revision 数量、摘要和引用,用 revision 替换保留证据。 -- 运行时持续回退主路径 embedding 配置可能静默改变向量空间,插件持有解析后的配置可避免此问题。 +- 多 rag Artifact 保留项目级 Scope,不把集合组织与授权绑定。 +- Source journal 持久保存已接受操作,无需新增可变任务表;仅内存命令在重启时会丢失。 +- 请求 Source 保存意图,精确成功编辑 Source 保存结果;提前使用后者会错误表达溯源。 +- Source 生命周期字段表达通用删除,payload 仍不可变;文档专用 sidecar 重复承担该职责。 +- 整篇 manifest 配合 chunk 明细避免巨大正文 JSON 和逐 chunk Artifact 身份。 +- 不可变 revision 替换保留旧数量/摘要/引用,直接删 chunk 做不到。 +- 独立任务/发布系统可提供更丰富的状态/切换能力,但不在接受范围内。 # 既有设计 基于 [Source 插件](2012-source-plugin-system.md)、[Artifact 插件](2175-artifact-plugin-system.md)、 [Source 身份](1400_source_definition_and_observation_model.md)、[处理监督](1515_artifact_processing_supervisor.md) -和 [Source/Artifact API](1437_source_artifact_rest_api.md)。现有 OpenDAL 已比较路径/内容 hash,Artifact head 治理和通用片段索引 -提供复用基础,但并不表示知识库已经实现。Atomic Memory retirement 可参考,但不等于已有 Source 到 document 的级联契约。 +和 [Source/Artifact API](1437_source_artifact_rest_api.md)。现有 OpenDAL hash、Source cursor CAS、Artifact head 治理和片段索引 +提供基础,并非完整知识库实现。Atomic Memory retirement 也不等于已存在 Source 到 document 的级联契约。 # 待解决问题 -实现需要固定能力签名、支持图片格式/模型版本、资源限制、后端迁移/事务行为,以及依据实际 embedding token 限制验证的默认参数。 -验证三表基线,不预先扩大。任何核心 schema 改动必须有真实缺口和评审依据。 - -永久擦除、恢复、保留/GC、改名身份、完整批次历史、逐 rag 独立 embedding/重建和完整编辑 Markdown 导出需要另定契约。 -不能直接拼接重叠 chunks 声称得到准确的编辑全文。 +实现时固定 Source/capability 签名、图片/模型版本、资源与切块默认值、有限重试错误分类、后端迁移/索引事务行为。 +新增查询投影必须有测量依据。逐请求持久结果、恢复/擦除/GC、改名身份、逐 rag 向量空间和完整编辑 Markdown 导出另定契约, +不能直接拼接重叠 chunks 重构完整编辑文档。 # 后续可能性 -更多 OpenDAL provider、解析器、切块策略、rerank 和受限 agentic 检索可扩展组件边界。 -测量到实际存储压力后可考虑共享不可变 chunk 正文,这些都不是首期归属、去重、原子提交或精确证据的前置条件。 +通过组件边界扩展 OpenDAL provider、解析器、切块器、rerank 与受限 agentic 检索。测量后再考虑共享不可变 chunk 正文、 +更丰富任务状态或面向集合规模的查询投影,这些都不是首期归属、请求恢复、版本内容和精确证据的前置条件。 From e9a4ebf50478de3fb3bb11539a12c49dd6655942 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Wed, 11 Nov 2026 11:19:44 +0800 Subject: [PATCH 06/13] docs(rfc): define chunk read APIs and local ingestion --- docs/en/rfcs/2570-rag-knowledge-base.md | 100 ++++++++++++++++++++---- docs/zh/rfcs/2570-rag-knowledge-base.md | 85 ++++++++++++++++---- 2 files changed, 153 insertions(+), 32 deletions(-) diff --git a/docs/en/rfcs/2570-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md index 4996308275..5d5a7fd161 100644 --- a/docs/en/rfcs/2570-rag-knowledge-base.md +++ b/docs/en/rfcs/2570-rag-knowledge-base.md @@ -64,13 +64,16 @@ Scope separate original Sources, requests, and documents Source plugin: OpenDAL capture, snapshot access, original and trusted operation Source types -Document plugin: Markdown / OCR, chunks, revision writes, operation consumption and provenance -rag plugin: collection configuration, retrieval policy and chunk index adaptation +Document plugin: Markdown / OCR, chunks, revisions, operation consumption, provenance and chunk index lifecycle +rag plugin: collection configuration and retrieval orchestration over document chunks Shared facilities: Source/Artifact APIs, Supervisor/Worker, cursor, transactions, database/model adapters ``` The three logical plugins may ship in one package. The application service coordinates them; it is not a fourth plugin. A rag can exist without Sources. Its configuration uses Artifact revisions, and deletion uses head governance. +The knowledge-base Scope enables only document business: document Sources, document Artifacts, and pre-created rag +Artifacts. Operation and edit-evidence Sources are internal records of that same pipeline, not inputs to other families. +Scope admission and consumer bindings enforce this restriction; no new Scope table is required. There is no rag runtime table. Ownership is explicit in immutable Source payloads and document manifests, not inferred from tags or evidence lineage. Each original, request, and document has one owner rag. @@ -91,6 +94,13 @@ must run where the selected path exists. Fix root, relative-path, and symlink no before acceptance, hash the exact saved bytes, and parse that snapshot, not a later read of a changing file. mtime/size are hints, not proof of equality. Preserve the first canonical capture metadata when reusing an existing Source. +The first phase supports only locally accessible directories, using the OpenDAL `fs` backend. The importer, Server, +and Worker must access the same managed snapshot directory, directly or through local container volume mappings. +Check storage configuration/access before accepting processing requests. Store `original_path` for provenance and +`snapshot_ref={store_id, object_key, digest}` for actual reads; resolve the storage alias to each process's configured +local root. Worker reads the captured snapshot even if the user later edits or removes the original file. Remote +client uploads, cross-machine file transfer, object-storage originals, and remote shared storage are outside this phase. + ```text file_key = (scope_id, rag_id, collection_id, normalized_relative_path) document_id = stable_hash(identity_version, file_key) @@ -122,6 +132,11 @@ not the largest original Source journal position. Finding a Source is not proof Renames create new identities initially; absent files do not imply deletion. Deleted Source identities and retired document heads must not be silently resurrected. +Parser/chunker choice is not part of document identity. Explicit reprocessing of the same Source with a new splitting +method keeps the same `document_id` and `rag_id`, and commits the next revision only after content/index preparation +succeeds. It replaces the current effective content/indexes, not historical rows. Failure leaves the old head usable; +manual modifications still require explicit discard authorization. Rechunking may assign new chunk IDs. + Reuse Source `collect` discovery/add/status/control. A client-generated `scan_token` in plugin input identifies one explicit scan; retrying that input reuses its collection target. A new explicit scan has a new token but the same file identities. Scan once per token; do not imply periodic sync or that repeated add restarts a stopped target. @@ -177,7 +192,8 @@ Backfill existing Sources as active. Payload, identity, and journal position rem excluded from content hashing. Use row locking/conditional updates and consistent lock ordering against document commits; no separate Source deletion-generation column is required initially. Adapt add/get/list, evidence and generation access, and family reads. Duplicate add of a deleted identity must not return usable content or reactivate it. Internal -migration/cascade scans may include deleted rows; public reads cannot bypass deletion. Verify additive migrations on +migration/cascade scans may include deleted rows; public reads cannot bypass deletion. This phase exposes deletion for the knowledge-base pipeline's originals and +internal records only, not unrelated Source types or cross-family cascades. Verify additive migrations on SQLite, SeekDB, and OceanBase rather than treating Artifact retirement as existing Source soft-deletion support. The only new domain table is `pc_document_chunks`: @@ -191,9 +207,12 @@ The only new domain table is `pc_document_chunks`: | Provenance | Normalized spans, original byte/image locators, origin/verbatim, base/edit references | Use backend-safe keys and bounded metadata. Each revision is a complete immutable chunk snapshot: removing one of -100 chunks produces a new manifest and 99 rows, preserving the original 100. Manifest fields include owner rag, -file identity, root SourceRef, schema/processing fingerprint, chunk count/digest, manual-change flag, and -`applied_request_ref`. History uses exact revisions, not today's head. +100 chunks produces a new manifest and 99 rows, preserving the original 100. The existing Artifact envelope identifies +the document/revision; its bounded manifest contains title, owner rag, file identity, root SourceRef, processing +fingerprint, chunk count/digest, manual-change flag, and `applied_request_ref`. A client derives the chunk-directory +route from the exact document reference. Do not embed chunk bodies or an unbounded list of chunk IDs in the manifest. +History uses exact revisions, not today's head. Chunk rows also supply `text_length`, measured in Unicode code points, +for metadata-only directory reads without returning body text. Initially, membership and availability may require paginated Scope/type scans and payload decoding plus exact Artifact reads by deterministic document ID. Do not assume canonical payloads already have queryable JSON owner/path @@ -270,6 +289,14 @@ content-only path. Rebuild committed chunks without OCR, with explicit unavailab fallback or a zero-downtime promise. Verify real transaction behavior on all backends, including SQLite write locking; ANN limitations need filtered exact retrieval or a clear capability failure. +The document plugin owns one revision-aware chunk projection boundary used by initial writes, revision replacement, +rebuild, coverage verification, deletion filtering, and retrieval. Rebuild must load the exact committed chunk rows, +not expand the bounded manifest as full text. Coverage compares the manifest count/digest with that revision's chunks +and projections. A zero-chunk revision has valid zero-fragment coverage. Retrieval retains exact document revision +and chunk IDs through scoring/fusion so later chunk reads resolve the actual hit. Generic projection/rebuild code +needs this integration; adapting only the initial write path is insufficient. The rag service reuses these projections +without changing generic Artifact search result contracts. + ## 6. Editing, chunk removal, and deletion Validate edit `If-Match` both at acceptance and commit. A successful edit writes a whole new snapshot. Unchanged chunks @@ -305,7 +332,7 @@ from the retired parent and immutable ownership, including deleted rows internal Exclude invalid rows before ranking even while fan-out is incomplete. Derived indexes retain existing replacement, removal, and rebuild semantics; preserving business history does not promise every historical index entry stays intact. -## 7. Availability and unified APIs +## 7. Availability, Artifact APIs, and chunk access | Display | Derivation | | --- | --- | @@ -331,8 +358,11 @@ content; document files go through the Source plugin protocol. Let `R=/v1/scopes | List files and available results | Existing Source list/get and Artifact list/get/history, validated owner-rag filters, helper join by document ID; no `R/processing` task list | | Explicit reparse | POST `D/processing`, `source_ref`, `action=reprocess`, `request_id`, optional configuration/discard; 202 request acceptance | | Edit/remove chunk | POST `D/edits`, current `If-Match`, typed bounded operation and request ID; 202 request acceptance | -| Read chunks | GET `D/revisions/{rev}/chunks`, exact revision, `items/next_cursor` | -| Search | Existing POST `/v1/scopes/{s}/artifacts/document/search`, existing query/mode/limit/fusion, validated `filters.rag_ids` | +| Get document | Existing Artifact GET/history; title, exact revision, owner, chunk count and original reference, no chunk bodies | +| Chunk directory | GET `D/revisions/{rev}/chunks`; paginated ID/order/heading-path/text-length metadata only | +| Get one chunk | GET `D/revisions/{rev}/chunks/{chunk_id}`; body, provenance and manual-edit markers | +| Get chunks in a batch | POST `D/revisions/{rev}/chunks/batch-get`; bodies for an explicit bounded list of chunk IDs | +| Knowledge-base retrieval | New POST `/v1/scopes/{s}/rag/retrieve`; explicit `rag_ids`, query/mode/limit, chunk-reference results | | Soft-delete | DELETE on existing exact Source/Artifact routes; Artifact governance `expected_generation`, one-way Source lifecycle | Reparse with an existing head requires `If-Match`; without a head, use the deterministic document ID and @@ -374,18 +404,50 @@ Explicit reparse, with `If-Match` for an existing document and authorization to {"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} ``` -Search selected rags in one Scope: +Document GET and exact history retain the existing Artifact envelope with the bounded manifest. The directory +returns `items/next_cursor`, ordered by ordinal, with no body or excerpt. Its cursor binds Scope/document/revision; +concurrent head changes cannot mix revisions. Single and batch reads use that same exact revision, never today's head. +All three routes enforce owner/document/root lifecycle checks, including historical reads. A zero-chunk revision has +an empty directory. Single-item output includes text, source reference/locator, origin/verbatim and edit provenance. + +Batch-get accepts a nonempty unique `chunk_ids` list, returns items in request order, and does not accept mixed +revisions. Enforce configured ID-count and response-byte limits; reject oversized batches without truncating text. +Authorize the parent first, then validate every ID in that revision. A missing ID fails the batch with 404 rather +than silently omitting it; deleted resources follow the existing authorized 410 rule. These are read operations, +not a general bulk mutation API. + +Example directory response for one exact revision: + +```json +{"document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +``` + +Batch request to POST `D/revisions/2/chunks/batch-get`: + +```json +{"chunk_ids":["chunk-1","chunk-2"]} +``` + +Knowledge-base retrieval uses POST `/v1/scopes/{s}/rag/retrieve`, not the generic Artifact search response: + +```json +{"rag_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +``` + +Return bounded chunk hits with rag ID, exact document reference, chunk ID, score, and source locator; optional snippets +are bounded and do not replace the full-body chunk API. Here `limit` counts chunk hits. For example: ```json -{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} +{"hits":[{"rag_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` -Search results retain complete bounded document manifests and lineage. Add optional typed `matches` for bounded exact -chunk hits, including revision/chunk ID, text, locator, origin/verbatim, and scores. This projection is not stored in -Artifact content. `limit` counts documents; fragments per document have a separate cap. Reject unsupported filters or -rerank options explicitly; missing rag selection must not broaden the search. Cross-Scope helpers authorize explicit -`(scope, rag)` targets, invoke the same per-Scope search, rank-fuse, and retain target errors/identities. Do not compare -incompatible raw scores or introduce a separate `/rag/query` protocol. +The generic Artifact GET/history and search contracts remain intact: Artifact searches return Artifacts, not arbitrary +chunks or another family's documents. A document-specific internal handler can reuse index/model facilities; the +separate rag retrieval route avoids adding knowledge-base matches to every generic search item. Require nonempty +validated rag selection and filter ownership/lifecycle before ranking. Unsupported filters/rerank options fail clearly. +Cross-Scope helpers authorize explicit `(scope, rag)` targets, call the same per-Scope rag retrieval route, rank-fuse, +and retain target errors/identities. Do not compare incompatible raw scores. HTTP, Python and MCP expose equivalent +metadata, chunk-read and retrieval operations, reusing common authorization and errors. At acceptance use existing 428/412 preconditions, 409 payload/discard conflicts, authorized 410 deletion, 422 validation (or transport 413), and 503 service unavailability with the existing `error.code/message/details` envelope. After 202, @@ -409,6 +471,10 @@ Run the same public workflow against SQLite, SeekDB, and OceanBase: - Versioned chunk removal including the last chunk, complete history and correct current indexes. - Source/document/rag deletion races, recoverable cascade, replacement-root independence. - Independent plugin configuration, index isolation, rebuild unavailability, pagination, contract generation and SDK/MCP parity. +- Metadata-only document/directory reads, exact-revision single/batch chunk bodies, byte/count bounds and missing-ID behavior. +- Same-Source rechunking keeps document/rag identity while replacing the current revision and retaining history. +- Chunk projection/rebuild/coverage parity, including zero chunks and exact retrieval-hit resolution. +- Local OpenDAL snapshots accessible to importer/Worker, including container mappings; no remote-path acceptance. Mocks do not establish real backend/OCR support. Use #2441 for ingestion/ownership/Source lifecycle, #2442 for processing, requests/chunks/atomic writes, #2443 for retrieval/interfaces, and #2444 for diagnostics/acceptance. One implementation diff --git a/docs/zh/rfcs/2570-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md index 59c55a1991..0932675081 100644 --- a/docs/zh/rfcs/2570-rag-knowledge-base.md +++ b/docs/zh/rfcs/2570-rag-knowledge-base.md @@ -56,13 +56,15 @@ Scope 独立的原文 Source、请求和 document Source 插件:OpenDAL 采集、快照访问、原文与受信操作 Source 类型 -Document 插件:Markdown/OCR、chunks、revision 写入、操作消费和溯源 -rag 插件:集合配置、检索策略和 chunk 索引适配 +Document 插件:Markdown/OCR、chunks、revision、操作消费、溯源与 chunk 索引生命周期 +rag 插件:集合配置与 document chunk 检索编排 共享设施:Source/Artifact API、Supervisor/Worker、cursor、事务、数据库/模型适配器 ``` 三个逻辑插件可放在同一集成包,应用服务负责协调,不新增第四个插件。Rag 可先于 Source 存在,配置使用 Artifact revision, -删除使用 head 治理,不设 rag 运行状态表。归属显式保存在不可变 Source payload 和 document manifest,不从 tags 或证据 lineage 推断。 +删除使用 head 治理。知识库 Scope 只启用文档业务:文档 Source、document 和预创建的 rag;请求/编辑证据是这条管线的内部记录, +不是其他 family 的输入。通过 Scope 接受规则和消费 binding 执行限制,无需新增 Scope 表。 +不设 rag 运行状态表。归属显式保存在不可变 Source payload 和 document manifest,不从 tags 或证据 lineage 推断。 每个原文、请求和 document 只属于一个 rag。 插件独立持有 embedding/索引配置。显式配置优先;安装时可从主路径初始化兼容的缺省项,并固定解析后的 profile 和凭据引用。 @@ -78,6 +80,11 @@ OpenDAL/opendalfs 负责本地列举/读取和受管目录中的不可变快 符号链接规范化策略,拒绝越界。先保存快照,再接受 Source,对保存字节计算 hash 并解析该快照,不能解析随后变化的文件。 mtime/size 仅是提示,不证明内容相同。复用已有 Source 时保留首次 canonical 采集信息。 +首期仅支持本地可访问目录,使用 OpenDAL fs 后端。导入进程、Server 和 Worker 必须能访问同一受管快照目录, +可直接访问或使用本机容器卷映射;接受处理请求前校验存储配置与访问能力。Source 用 original_path 记录出处, +用 snapshot_ref(store_id、object_key、digest)供实际读取,存储别名解析到各进程配置的本地根目录。 +原文件随后修改或移除,Worker 仍读取已采集快照。远端客户端上传、跨机器文件传输、对象存储原文和远端共享存储均不在本期范围。 + ```text file_key = (scope_id, rag_id, collection_id, normalized_relative_path) document_id = stable_hash(identity_version, file_key) @@ -107,6 +114,10 @@ Collection 由已注册存储实例/绑定和规范化根目录派生,不使 找到 Source 不证明当前 document 已匹配。首期改名视为新身份,目录文件消失不自动删除。已删除 Source 身份与 retired document 不能被静默恢复。 +Parser/chunker 选择不参与 document 身份。同一 Source 改用新的切分方法时,显式重解析沿用 document_id 和 rag_id, +内容/索引准备成功后提交下一个 revision,替换当前有效内容和索引,不覆盖历史行。失败保留旧 head; +已有人工修改仍需明确 discard 授权。重新切块可以产生新的 chunk ID。 + 复用 Source collect 的发现/add/status/control。客户端生成的 scan_token 放在插件 input 中标识一次显式扫描;重试相同输入 复用采集目标。再次扫描使用新 token,但文件身份不变。每 token 扫描一次,不暗示定时同步或重复 add 会启动 stopped target。 采集状态仅描述接入;扫描还需检查成功 document 结果,不能只看 checkpoint。 @@ -155,7 +166,8 @@ Chunk metadata 保存有界出处映射,canonical chunks 不存向量,Artifa 已有 Source 回填 active,payload、身份和 journal position 保持不可变,生命周期元数据不参与内容 hash。 通过行锁/条件更新和统一锁定顺序与 document 提交互斥,首期不额外增加 Source 删除代次列。 适配 add/get/list、证据/生成访问和 family 读取;重复 add 命中已删身份时不能返回可用内容或恢复。 -内部迁移/级联扫描可包含已删行,公共读取不能绕过。三个后端验证加法迁移,不能把 Artifact retirement 当作已有 Source 软删除能力。 +内部迁移/级联扫描可包含已删行,公共读取不能绕过。本期删除能力只覆盖知识库管线的原文和内部记录, +不扩展到无关 Source 类型或其他 family 级联。三个后端验证加法迁移,不能把 Artifact retirement 当作已有 Source 软删除能力。 唯一新增领域表为 pc_document_chunks: @@ -168,8 +180,10 @@ Chunk metadata 保存有界出处映射,canonical chunks 不存向量,Artifa | 溯源 | 规范化跨度、原文字节/图片定位、origin/verbatim、base/edit 引用 | 使用后端安全键长与有界元数据。每个 revision 是完整不可变 chunk 快照:100 块移除一块生成新 manifest 和 99 行,保留旧的 100 行。 -Manifest 保存 owner rag、文件身份、root SourceRef、schema/处理指纹、chunk 数量/摘要、人工修改标记和 applied_request_ref。 -历史读取使用精确 revision,而非当前 head。 +现有 Artifact 封装标识 document/revision,有界 manifest 保存标题、owner rag、文件身份、root SourceRef、处理指纹、 +chunk 数量/摘要、人工修改标记和 applied_request_ref。客户端由精确 document 引用确定 chunk 目录路径; +manifest 不嵌入 chunk 正文或无界 chunk ID 列表。历史读取使用精确 revision,而非当前 head。 +Chunk 行提供 text_length(Unicode 码点数量),供目录只返回长度等元数据,不返回正文。 首期成员和可用性查询可以按 Scope/类型分页扫描解码 payload,再按确定性 document ID 精确读 Artifact。不能假设 canonical payload 已具备可查询的 JSON owner/path 索引。过滤分页按扫描位置继续,不能丢失后续匹配项;写入/读取验证归属和完整身份。 @@ -233,6 +247,11 @@ Cursor 表示已消费,包含跳过,不表示成功。成功 revision 通过 重建读取已提交 chunks,不重复 OCR;明确不可用,不回退 Memory/纯全文,也不保证零停机。 三个后端需验证实际事务,包括 SQLite 写锁;ANN 过滤限制需通过限定集合精确检索或明确能力错误处理。 +Document 插件负责统一的精确版本 chunk 投影边界,覆盖首次写入、版本替换、重建、coverage 校验、删除过滤和检索。 +重建读取精确已提交 chunk 行,不能把有界 manifest 当全文。Coverage 核对 manifest 数量/摘要、该 revision 的 chunks 与投影; +零 chunk revision 对应合法的零片段 coverage。评分/融合保留精确 document revision 和 chunk ID,使后续读取能定位实际命中。 +通用投影/重建代码需要接入该边界,只适配首次写入不足以完成实现。Rag 服务复用这些投影,不改变通用 Artifact 搜索结果契约。 + ## 6. 编辑、chunk 移除与删除 编辑 If-Match 在接受和提交时分别校验,成功生成完整新快照。未变 chunk 保留逻辑 ID,重切块分配新 ID;引用始终带 revision。 @@ -261,7 +280,7 @@ Remove 同样算人工修改,重新解析需明确丢弃授权。完整 embedd 内部包含已删行,无需 cascade job 表。即使传播未完成,也必须在排名前排除无效对象。 派生索引沿用替换/移除/重建;保留业务历史不等于保留每个历史索引条目。 -## 7. 可用性与统一接口 +## 7. 可用性、Artifact 接口与 chunk 读取 | 展示 | 推导依据 | | --- | --- | @@ -285,8 +304,11 @@ Rag 配置变化影响后续请求,可提示需要重处理,但不自动入 | 文件与可用结果列表 | 现有 Source list/get、Artifact list/get/history,验证 owner-rag filter,helper 按 document ID 合并;不设 R/processing 任务列表 | | 显式重解析 | POST D/processing,source_ref、action=reprocess、request_id、可选配置/discard;202 表示请求接受 | | 编辑/移除 chunk | POST D/edits,当前 If-Match、有界类型化操作和 request ID;202 表示请求接受 | -| 读取 chunks | GET `D/revisions/{rev}/chunks`,精确版本、items/next_cursor | -| 检索 | 现有 POST `/v1/scopes/{s}/artifacts/document/search`,query/mode/limit/fusion,经过验证的 filters.rag_ids | +| 获取 document | 现有 Artifact GET/历史接口,返回标题、精确版本、归属、chunk 数量和原文引用,不返回 chunk 正文 | +| 获取 chunk 目录 | GET `D/revisions/{rev}/chunks`,分页返回 ID/顺序/标题路径/长度等元数据 | +| 获取单个 chunk | GET `D/revisions/{rev}/chunks/{chunk_id}`,返回正文、出处和人工修改标记 | +| 批量获取 chunk | POST `D/revisions/{rev}/chunks/batch-get`,按明确且有界的一组 chunk ID 返回正文 | +| 知识库检索 | 新增 POST `/v1/scopes/{s}/rag/retrieve`,明确 rag_ids、query/mode/limit,返回 chunk 命中引用 | | 软删除 | 在既有精确 Source/Artifact 路由增加 DELETE;Artifact 治理 expected_generation,Source 单向生命周期 | 已有 head 的重解析需 If-Match,无 head 时使用确定性 document ID 和 If-None-Match: *。验证 Source 归属/文件身份确实解析到该 ID, @@ -326,16 +348,45 @@ current_revision_at_accept 是观察值,不是输出。通过 revision 的 app {"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} ``` -同 Scope 检索选定 rag: +Document GET/精确历史沿用 Artifact 封装和有界 manifest。Chunk 目录使用 items/next_cursor,按 ordinal 排序, +不返回正文或摘要片段。Cursor 绑定 Scope/document/revision,head 并发变化不会混入其他版本;单个和批量读取也使用同一精确版本, +不回退当前 head。三个 chunk 入口均校验 owner/document/root 生命周期,包括历史读取。零 chunk revision 返回空目录。 +单个 chunk 返回 text、source_ref/locator、origin/verbatim 和编辑依据。 + +Batch-get 接受非空、无重复的 chunk_ids,按请求顺序返回,不允许混合 revision。限制配置的 ID 数量与响应字节数, +超限拒绝而非截断正文。先授权父对象,再验证该 revision 内的所有 ID;任一 ID 不存在则整个批次返回 404,不静默忽略。 +已删对象沿用授权后 410。该接口仅批量读取,不是通用批量修改接口。 + +一个精确 revision 的目录响应示例: + +```json +{"document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +``` + +POST `D/revisions/2/chunks/batch-get` 请求: + +```json +{"chunk_ids":["chunk-1","chunk-2"]} +``` + +知识库检索使用 POST `/v1/scopes/{s}/rag/retrieve`,不套用通用 Artifact 搜索响应: + +```json +{"rag_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +``` + +结果为有界 chunk 命中,携带 rag ID、精确 document 引用、chunk ID、得分和原文定位;可选摘要片段必须有界,不能替代正文接口。 +这里 limit 计算 chunk 命中数。例如: ```json -{"query":"How should I restart a follower?","mode":"hybrid","limit":10,"filters":{"rag_ids":["ops"]},"include_scores":true} +{"hits":[{"rag_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` -搜索结果保留完整有界 document manifest 和 lineage,增加可选类型化 matches 表示有界精确 chunk 命中,携带 revision/chunk ID、 -text、locator、origin/verbatim 和得分。这是响应投影,不写入 Artifact content。Limit 计算文档数,每篇片段另有限额。 -不支持的 filter/rerank 明确拒绝,缺少 rag 选择不能扩大范围。跨 Scope helper 逐个授权明确的 (scope, rag),调用相同分 Scope 搜索, -按排名融合,保留目标错误/身份;不比较不兼容原始分数,不另建 /rag/query 协议。 +通用 Artifact GET/历史/搜索契约保持原义:Artifact 搜索返回 Artifact,不能随意返回 chunks 或另一 family 的 document。 +Document 专用内部处理器复用索引/模型设施,独立 rag 检索入口避免给所有通用搜索项增加知识库 matches。 +要求非空且经过验证的 rag 选择,排名前过滤归属和生命周期。不支持的 filter/rerank 明确报错。 +跨 Scope helper 逐个授权明确的 (scope, rag),调用同一分 Scope rag 检索接口,按排名融合并保留目标错误/身份,不比较不兼容原始分数。 +HTTP、Python、MCP 提供等价的概览、chunk 读取与检索操作,复用公共授权和错误封装。 接受阶段沿用 428/412 前置条件、409 payload/discard 冲突、授权后 410 删除、422 校验(传输层可用 413)和 503 服务不可用, 保持 error.code/message/details 错误封装。202 之后的请求局部失败/冲突按日志与消费规则处理,不提供持久错误状态端点。 @@ -357,6 +408,10 @@ SQLite、SeekDB、OceanBase 使用相同公开流程验证: - Chunk 移除包括最后一块,历史完整,当前索引正确。 - Source/document/rag 删除竞争,可恢复级联,替代 root 独立性。 - 插件配置独立、索引隔离、重建不可用、分页、契约生成和 SDK/MCP 一致性。 +- Document/目录只读元数据,精确版本的单个/批量 chunk 正文、字节/数量上限及不存在 ID 的行为。 +- 同一 Source 更换切块方法保留 document/rag 身份,更新当前 revision 并保留历史。 +- Chunk 投影/重建/coverage 一致,包括零块和检索命中精确定位。 +- OpenDAL 本地快照对导入进程/Worker 可访问,包括本机容器映射;不接受远端路径。 Mock 不证明真实后端/OCR 支持。#2441 负责接入/归属/Source 生命周期,#2442 负责处理、请求/chunks/原子写入, #2443 负责检索/接口,#2444 负责诊断/验收。一个实现分支/PR 可分阶段交付;RFC 不关闭实施 Issue,也不证明大规模容量。 From 449e9d0798138a0b3b4d4af056f3d070301b1811 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Wed, 11 Nov 2026 18:10:37 +0800 Subject: [PATCH 07/13] docs(rfc): define knowledge-base plugin and durable jobs --- docs/en/rfcs/2570-knowledge-base.md | 474 ++++++++++++++++++++++ docs/en/rfcs/2570-rag-knowledge-base.md | 519 ------------------------ docs/zh/rfcs/2570-knowledge-base.md | 397 ++++++++++++++++++ docs/zh/rfcs/2570-rag-knowledge-base.md | 450 -------------------- 4 files changed, 871 insertions(+), 969 deletions(-) create mode 100644 docs/en/rfcs/2570-knowledge-base.md delete mode 100644 docs/en/rfcs/2570-rag-knowledge-base.md create mode 100644 docs/zh/rfcs/2570-knowledge-base.md delete mode 100644 docs/zh/rfcs/2570-rag-knowledge-base.md diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md new file mode 100644 index 0000000000..2ad6cdc91c --- /dev/null +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -0,0 +1,474 @@ +--- +title: "RFC 2570: Knowledge Base document plugin" +description: "Provide document knowledge bases with one business plugin, an independent durable queue, and three plugin tables without changing existing Source or Artifact schemas." +--- + +- Proposal Name: `knowledge_base_plugin` +- Start Date: 2026-11-10 +- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) +- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) +- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) + +# Summary + +One `knowledge-base` business plugin provides local ingestion, parsing, chunking, version management, and hybrid retrieval. +A Scope may contain multiple user-created `knowledge-base` Artifacts. Each original Source and whole-file `document` Artifact +belongs exclusively to one knowledge base. Existing Source, Artifact, head, and lineage schemas remain unchanged; the plugin +adds resource, job, and chunk tables. Background processing does not use the existing Source consumption cursor. This is a +target design dependent on plugin framework extensions, not a statement of released functionality. + +# Motivation + +Business descriptions and SOPs need faithful originals, passage retrieval, predictable updates, and deletion. Parsing may be +slow or depend on external services, requiring durable work and per-file recovery. A business plugin should own these states +without adding knowledge-base fields to the shared Source model or blocking unrelated files behind one consumption cursor. +Artifacts continue to manage whole-document versions; separate chunks and indexes avoid reading large body JSON values. + +# Guide-level explanation + +1. Create an empty `knowledge-base` through the generic Artifact API, then import a local directory or files into it. +2. Ingestion returns a durable job ID. A UI can show queue state, processing stage, failure, completion, and the currently + available version; percentage progress is not required. +3. Markdown and independently imported text images use Markdown parsing and RapidOCR respectively, followed by shared + chunking, full-text/vector indexing, and document publication. +4. Changed originals or explicit reprocessing retain the document ID and publish a new revision on success. Failure keeps + the previous version available. +5. Manual chunk edits and removals also create document revisions and preserve history. Retrieval can select multiple + knowledge bases in the same Scope. +6. Deletion changes logical visibility while retaining business content, snapshots, and history. Ordinary, exact, historical, + evidence, and retrieval paths all enforce deletion. + +The first phase covers SQLite, SeekDB, and OceanBase; local OpenDAL fs; Markdown; RapidOCR with ONNX Runtime; rule-based +chunking; and manual editing. Embedded Markdown images retain their references without automatic fetching or OCR. A +large-corpus benchmark is not required. PDF/Office, scene-image understanding, remote uploads/original storage, periodic +directory synchronization, semantic/LLM chunking, restoration/permanent erasure, per-knowledge-base embedding spaces, and +uninterrupted index switching are outside this phase. Job status APIs are included; a complete management UI can build on +the same contract, and a scheduling mockup is not evidence of implementation. + +# Reference-level explanation + +## 1. One business plugin and naming + +The plugin registers dedicated document Source types, the `knowledge-base` and `document` families, background task entry +points, its storage migrations, and APIs. Ingestion, parsing, chunking, and retrieval are internal modules, not separately +installed plugins. The design assumes that [#2549](https://github.com/oceanbase/powercontext/pull/2549) and +[#2579](https://github.com/oceanbase/powercontext/pull/2579) will provide the required composite registration, constrained +writes, and API extensions; their proposed contracts are not treated as released interfaces. + +| Location | Identifier | +| --- | --- | +| Display name | Knowledge Base | +| Plugin and knowledge-base family | knowledge-base | +| Whole-document family | document | +| Ownership / multi-base selection fields | knowledge_base_id / knowledge_base_ids | +| Module and configuration prefix | knowledge_base | +| Plugin table prefix | pc_knowledge_base_ | + +```mermaid +flowchart TD + S[Scope] --> K1[knowledge-base K1] + S --> K2[knowledge-base K2] + K1 --> R[Resource: stable file identity] + R --> O[Immutable original Source] + R --> J[Independent job] + O --> P[Parsing and rule-based chunking] + J --> P + P --> C[Immutable chunk result and indexes] + C --> D[document revision: bounded manifest] + E[lineage_only operation evidence] --> D + D --> Q[Knowledge-base retrieval and exact chunk reads] +``` + +Scope remains the authorization boundary. A knowledge-base Scope contains document Sources, documents, and knowledge bases; +operation evidence is internal. Ownership is explicit and validated rather than inferred from tags or lineage. Only the +document pipeline may consume original document Sources; originals are not lineage_only. Framework admission must cover +write notifications, startup reconciliation, automatic consumers, and manual generation. A Source type name or suppressed +notification is not isolation. Shared-database deployment relies on those generic extensions and does not require a separate +PC Server by default; isolation cannot be claimed before admission is implemented. + +The plugin owns its embedding/index profile. Installation may initialize compatible defaults from the main configuration, +without following subsequent changes. Credentials remain deployment configuration. Initially, documents in a Scope share +the plugin profile; parsing/chunking may vary by knowledge base. Jobs and result metadata pin the relevant profiles. + +## 2. OpenDAL, identity, and deduplication + +The first phase accepts only directories accessible to the plugin runtime. Importer, Server, and Worker use the same storage +alias to access a managed immutable snapshot directory, including local container volume mappings. OpenDAL fs does not make +a remote client's path accessible. Enforce root containment and a fixed symbolic-link policy. + +A Source records `original_path` for provenance and `snapshot_ref` with store_id, object_key, and digest for reading. Save the +snapshot and calculate SHA256 from its actual bytes before durable job acceptance. Parse the snapshot, not a mutable original. +mtime/size are hints, not content identity. + +```text +file_key = (scope_id, knowledge_base_id, collection_id, normalized_relative_path) +document_id = stable_hash(identity_version, file_key) +source_key = stable_hash(source_schema_version, file_key, raw_content_digest) +processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) +index_key = hash(complete embedding inputs, plugin profile and projection versions) +``` + +Collection identity comes from the storage instance and normalized root, independent of scan/job IDs. Compare complete +identities on hash matches and never truncate paths. A Source payload pins ownership, document ID, file identity, media type, +digest, and snapshot. Replay preserves canonical capture metadata, including the original capture time. + +| Case | Behavior | +| --- | --- | +| Same request key and parameters | Return the same job/determined result; different parameters under that key conflict | +| Same file bytes/profile with an available result | Reuse Source/document, verify index availability, skip parsing | +| Different request key matching an active target | Return 409 with the existing job reference; do not duplicate execution | +| Changed original bytes | New Source, same document ID, new target generation and job | +| Explicit reprocessing / changed chunking profile | Reuse Source and document ID; publish a new revision on success | +| Only embedding/index configuration changes | Rebuild from committed chunks without repeating OCR | +| Same bytes at a different path / knowledge base | Separate logical Sources/documents; physical snapshots may be shared | +| Manual edits exist | Ordinary duplicate import preserves them; reprocessing requires manual_edits_policy=discard | + +An existing Source does not prove processing succeeded. Reverting file bytes may reuse an older Source; the resource's latest +target, not journal order, defines desired input. Renaming initially means a new file; disappearance does not automatically +delete it. Reimport never silently restores a deleted identity. Explicit reprocess is not skipped as ordinary import merely +because its output might be identical. + +## 3. Lightweight parsing and chunking + +A parser accepts a snapshot reference and pinned configuration, returning Markdown, source locators, and optional warnings. +An internal format registry selects Markdown or image parsing. Future formats add a parser and fixtures without requiring a +universal document AST, capability negotiation, or a separate parser plugin system. Parsers do not write Artifacts, job state, +or indexes. An external adapter may return a pending reference that the execution layer persists and resumes. + +Markdown uses markdown-it-py for structure and source mapping. Images use RapidOCR with ONNX Runtime, retaining boxes, order, +confidence, and preprocessing coordinate transforms. Normalization produces Markdown without inventing complex headings, +tables, or diagram semantics. Map normalized spans back to the image and declare locator precision. Derived Markdown never +replaces the original Source. + +- Group by headings/content blocks, recursively splitting oversized blocks. Without reliable headings, recursively split + paragraphs and sentences. +- Preserve code, tables, and list steps where possible. Split oversized tables by rows with headers and oversized code with + language/continuation metadata; hard limits still apply. +- Apply overlap to split long passages rather than mechanically across sections. Include Chinese punctuation boundaries. +- Preserve heading paths and original locators. Validate the complete embedding input, including heading prefixes, against + the model token budget; character counts are not token counts and silent truncation is forbidden. +- Parameters include max_chunk_chars and overlap_chars; 1200/100 are examples to validate, not quality claims. +- Validate UTF-8, image decoding/pixel limits, model versions, and resource limits. No-text OCR is an explicit failure, not a + successful empty document. + +Rules remain deterministic and testable. Changed chunking configuration may reuse validated parsing output; a complex stage +cache is not required initially. + +## 4. Persistence and relationships + +### 4.1 Reuse existing schemas unchanged + +| Table | Responsibility | +| --- | --- | +| pc_sources | Immutable original references and lineage_only evidence for successful user/deletion operations; no new columns | +| pc_artifacts | Knowledge-base configuration, document manifests, immutable revisions | +| pc_artifact_heads | Current revision, lifecycle_state, governance_generation | +| pc_artifact_lineage_sources / pc_artifact_lineage_artifacts | Exact-revision input/operation evidence and base references | +| Existing permissions, tags, and references | Shared semantics, without unbounded jobs or member JSON | + +Existing processing intent, cursor, lease, and binding-state tables are not used by this queue and receive no knowledge-base +fields or records. Source journals may remain part of existing storage constraints but never drive job discovery/completion. + +### 4.2 Three plugin domain tables + +Tables belong to plugin-owned storage and migrations, reusing SQLite/SeekDB/OceanBase connection and adapter capabilities. +Full-text/vector auxiliary structures are not included in the domain-table count. + +| Table | Key fields and constraints | +| --- | --- | +| pc_knowledge_base_resources | scope_id, knowledge_base_id, resource_kind, resource_key, document_id, source_ref, identity_payload, lifecycle_state, deleted_at, target_generation, current_job_id | +| pc_knowledge_base_jobs | job_id, scope_id, knowledge_base_id, document_id, operation, idempotency_key, request_digest, input_snapshot, target_generation, base_revision, state, stage, attempt, next_run_at, execution_token, lease_owner, lease_expires_at, error_code/summary, external_task_ref, result_id, result_revision, result_kind, parent_job_id, checkpoint, cleanup_cursor | +| pc_knowledge_base_chunks | scope_id, knowledge_base_id, document_id, result_id, chunk_id, ordinal, text, text_length, content_digest, heading_path, source_locator, origin, edit_metadata | + +Resources has exactly two record kinds, not an open-ended object platform: + +- `document`: one row per stable logical file, created before the first parse; path identity, current target, and deletion + marker, without precreating an empty document Artifact. +- `source`: one row per original Source with ownership and its independent deletion marker; no growing JSON array of versions. + Successful operation evidence inherits visibility from its target Artifact. + +The primary key is `(scope_id, knowledge_base_id, resource_kind, resource_key)`. Document keys derive from file_key; Source +keys include a hash of the complete SourceRef identity. Preserve/compare complete identities and prohibit cross-base Source +ownership. SourceRef includes both source_type and source_id. Only document rows use target generation/current job fields. +Deletion markers are one-way. The published revision comes only from the Artifact head, without a second publication pointer. +Implementation fixes common timestamps and bounded error/JSON storage types. + +Jobs has a unique constraint on `(scope_id, knowledge_base_id, operation, idempotency_key)`. Its request digest covers all +business parameters and preconditions. Index due jobs, expired leases, document references, and knowledge-base ownership. +The target row serializes requests per document rather than relying on backend-specific partial unique indexes. Terminal jobs +retain idempotent receipts; bounded errors and attempt counters avoid separate receipt/attempt tables. + +Chunks uses primary key `(scope_id, knowledge_base_id, document_id, result_id, chunk_id)` and unique ordinal within a result. +`result_id` identifies immutable output before core allocates the actual revision; never guess the next revision when writing. +Each complete result has its own chunk snapshot; vectors are derived indexes. `text_length` counts Unicode code points. + +The bounded document manifest contains title, knowledge_base_id, file identity, root SourceRef, result_id, chunk count/digest, +processing/index fingerprints, manual-edit marker, applied_job_id, and necessary operation summaries. It contains neither +body text nor an unbounded chunk ID list. Exact revisions resolve results through their manifests, independently of current +search indexes. + +## 5. Independent queue and state machine + +```mermaid +stateDiagram-v2 + [*] --> queued + queued --> running + running --> succeeded + running --> retry_wait + retry_wait --> running + running --> waiting_external + waiting_external --> queued + running --> failed + queued --> cancelled + running --> cancelled + waiting_external --> cancelled + retry_wait --> cancelled + queued --> superseded + running --> superseded + waiting_external --> superseded + retry_wait --> superseded +``` + +`stage` is independent of state: ingest, parse, chunk, index, publish, cleanup. External waits persist a remote reference and +next_run_at, then release the Worker. A later poll resumes work without holding a process or transaction. Remote submissions +use stable idempotency keys; services without idempotency need reconciliation, not a promise of exactly-once external calls. + +KnowledgeBaseTaskSupervisor scans only plugin jobs and owns claim, heartbeat, expiry recovery, and completion. Reuse separable +process-launch/termination, budget, and shutdown tools. Do not attach to existing Scope/binding discovery, intents, or Source +cursors. If the existing Supervisor is coupled to those mechanisms, implement a lightweight plugin scheduler rather than +putting per-file jobs into its tables. Publication is serial per document, with bounded concurrency across documents. + +`target_generation` identifies the desired result; `execution_token` identifies the currently authorized attempt. Claims, +heartbeats, and updates check the token. New targets supersede old targets; lease recovery rotates the token. SQLite uses its +actual transaction/CAS capabilities rather than assuming every backend supports SKIP LOCKED. + +After authorization/lifecycle checks, recognize accepted idempotent replays before checking the current base for new requests; +a successful network retry must not fail solely because its original ETag is stale. Terminal jobs never revive. Automatic +bounded retries remain within a job; user retries after terminal failure use a new key/job. Cancellation does not undo a +published result. Edits/removals pin their base and reject conflicting active changes rather than silently queue or rebase. +A failed file does not block the whole Scope. + +## 6. Acceptance, publication, and cross-store recovery + +Core and plugin storage do not share a transaction. Source, job, chunks, indexes, and Artifact cannot be described as one atomic +commit. + +| Boundary | Behavior and recovery | +| --- | --- | +| Snapshot | Save immutable original bytes; unaccepted orphan snapshots are invisible, with permanent cleanup specified separately | +| Plugin acceptance transaction | Validate/lock the resource target, check idempotency, persist fixed inputs and job; recoverable after 202 | +| Source registration | Worker idempotently saves/reuses the Source in the ingest stage; retry if Source succeeded but job acknowledgement did not | +| Computation outside transactions | Parse/OCR/chunk/embed pinned snapshots and settings without database locks | +| Plugin result preparation | Store complete immutable chunks and usable indexes under result_id; verify count/digest; unreferenced output is invisible | +| Short core publication transaction | Check base, ownership, and execution eligibility; write document revision, required operation evidence Source, lineage, and head | +| Plugin completion transaction | Record actual result_revision and succeeded; reconcile applied_job_id/result_id after lost acknowledgement rather than republish | + +Publication, deletion, target replacement, cancellation, and lease recovery must share a commit-eligibility gate. During short +publication, lock/validate the relevant plugin resource/job records through completion of the core commit. The constrained +writer also checks the knowledge-base head, document base, and lifecycle. Use a fixed lock order; no model calls, index builds, +or DDL inside the gate. Releasing plugin locks before core revision CAS would allow an obsolete token or deleted Source to +publish. Parent deletion must also serialize with the publication parent-state check, not merely an early task-start check. + +If core succeeds but the plugin transaction fails, recovery first reconciles the determined result in the manifest/lineage. +Target replacement and cancellation also reconcile first so that a published success is not recorded as cancellation. +Prepared results are never overwritten; recomputation producing different content uses a new result_id. Failed publication +keeps the old head and its searchable index. Validate these short transactions and lock order on all three backends without +introducing or pretending to provide distributed atomic transactions. + +## 7. Operation evidence, editing, and soft deletion + +Successful Artifact creation, modification, and deletion require a system `lineage_only` Source associated with the actual +output revision. Queued requests are not evidence of successful mutation. Reuse existing create/replace evidence semantics; +a bounded operation summary records specific delete/remove actions and reasons without assuming a new core operation enum. +Jobs record intent/execution; operation Sources record success, linked through job/operation IDs. + +| Operation | Version and visibility | +| --- | --- | +| Create/configure knowledge-base | Create or add a configuration revision with operation evidence | +| Parse/reprocess document | Publish a revision under the same document ID with original lineage; retain evidence for user-triggered changes | +| Edit/remove chunk | Increment document revision, produce a complete result, link successful operation evidence, retain previous rows | +| Delete document/knowledge-base | Create a deletion revision with a bounded deletion summary and retire the head in the same core transaction; link deletion evidence | +| Delete original Source | Mark the source resource; cancel dependent work; if the current document depends on it, perform recoverable document deletion with evidence | + +Deletion revisions are a plugin convention, not a change to other families' governance. A deletion revision may reuse the +previous result_id without copying chunk bodies. Its operation summary must actually create a revision rather than be skipped +by an identical-content put no-op. Evidence, lineage, revision, and head commit together in core; failure creates no success +evidence, and replaying the same accepted operation does not add revisions. + +Manual text replacement may retain a logical chunk ID, but references include a revision. Rechunking may create new IDs. +Edited text is marked non-verbatim with original locators and edit provenance. Removing the last chunk permits a zero-chunk +result with no current retrieval hits. Duplicate import cannot overwrite manual edits; explicit reprocessing requires discard. + +Knowledge-base deletion first commits its deletion revision/retirement, immediately hiding all children. An accepted cleanup +job survives restart, marks Sources, deletes documents, and cancels processing in batches. Each changed Artifact gets its own +evidence, sharing an operation ID for the cascade. Cleanup is allowed under a deleted parent and is not cancelled by ordinary +processing parent checks. Its persisted cursor is plugin batch progress only. Persist the deletion/cleanup job before retiring the parent so cascade work cannot be lost. + +Deleting a document leaves its original Source readable. Deleting an unpublished replacement Source preserves an old result +based on another original. If S1 supplied an old revision and S2 supplied a complete reparse, deleting S1 preserves the current +version based only on S2 but blocks history that depends on S1. Resource markers and Artifact retirement may finish in stages; +reads check applicable parent, document, exact root, and Source markers without waiting for index cleanup. Generic Source, +exact/historical Artifact, and evidence reads require framework visibility extension points; plugin search filtering alone +does not satisfy deletion. Missing ownership registration fails closed rather than returning unguarded content. +Controlled internal recovery may inspect retired history for reconciliation; an authorized management route may expose bounded +cleanup status after deletion without exposing bodies or a public bypass parameter. + +## 8. APIs and retrieval + +Reuse Source encoding/identity/validation; Artifact CRUD/history/tags; authentication; permissions; ETags; pagination; +references; and error envelopes. File ingestion uses the plugin's Source acceptance capability, not a write path that triggers +old consumers. Expensive edits return 202 through job APIs rather than silently changing synchronous Artifact PUT into an +asynchronous success. Generic writes must not bypass job, version, evidence, or deletion rules. + +Routes are proposed contracts. Plugin APIs follow #2579; registration syntax follows the framework implementation: +`P=/v1/plugins/knowledge-base/api/scopes/{s}`, `D=/v1/scopes/{s}/artifacts/document/{d}`. + +| Operation | API / result | +| --- | --- | +| Create knowledge base | POST `/v1/scopes/{s}/artifacts`, family=knowledge-base | +| Knowledge-base/document overview and history | Generic Artifact GET/revisions, bounded manifest | +| Import local files/directory | POST `P/imports`, explicit knowledge_base_id, root/paths, idempotency_key; 202 job receipt | +| Reprocess/edit/delete/cleanup | POST `P/jobs`, typed operation, pinned target and preconditions; cleanup is internal-only; the same service handles existing synchronous deletion/governance entry points | +| Job list/detail | GET `P/jobs`, GET `P/jobs/{job_id}`, pagination, stage, state, bounded error, successful revision | +| Cancel | POST `P/jobs/{job_id}/cancel`, unpublished nonterminal work only | +| Chunk directory | GET `P/documents/{d}/revisions/{rev}/chunks`, paged metadata without body | +| Single chunk | Append `/{chunk_id}`, body, provenance, edit metadata | +| Batch chunks | Append `/batch-get`, POST bounded chunk_ids | +| Hybrid retrieval | POST `P/retrieve`, knowledge_base_ids, query, mode, limit; chunk hits | + +Plugin chunk routes retain Artifact document IDs/revisions. Their paths are separate from generic Artifact routes while +preserving exact-revision semantics: resolve result_id through that revision's manifest, never fall back to the current head. +Directory cursors bind Scope/document/revision and order by ordinal. Batch-get requires nonempty, unique IDs and preserves +request order. Authorize the parent first; any missing ID fails the whole batch with 404. Bound ID count and response bytes; +reject over-limit requests without truncating bodies. Authorized deleted reads return 410; zero-chunk directories are empty. + +Create a knowledge base: + +```json +{"family":"knowledge-base","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +``` + +Import a directory. Enumeration creates per-file jobs in bounded batches using parent_job_id. Directory completion means +enumeration/child acceptance finished, not that every file succeeded: + +```json +{"knowledge_base_id":"ops","root":"/work/docs","idempotency_key":"import-01"} +``` + +Remove a chunk. Existing documents require current If-Match; first generation uses an explicit no-head precondition rather +than guessing a future revision: + +```json +{"knowledge_base_id":"ops","document_id":"doc-1","operation":"remove_chunk","idempotency_key":"edit-03","base_revision":2,"input":{"chunk_id":"chunk-3"}} +``` + +```json +{"job_id":"job-03","state":"queued","document_id":"doc-1","target_generation":5} +``` + +```json +{"job_id":"job-03","state":"succeeded","result":{"document_id":"doc-1","revision":3,"kind":"created"}} +``` + +Exact-revision directory and batch reads: + +```json +{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +``` + +```json +{"chunk_ids":["chunk-1","chunk-2"]} +``` + +```json +{"knowledge_base_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +``` + +```json +{"hits":[{"knowledge_base_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} +``` + +Retrieval limit counts chunks; optional snippets are bounded and bodies use chunk APIs. Generic Artifact search still returns +Artifacts rather than chunk responses. Index candidates must match the current manifest result_id and index profile and pass +ownership, authorization, and deletion checks. Refill after filtering so invalid candidates do not consume top-k. The adapter +covers initial writes, revision replacement, rebuild, coverage/digest validation, zero chunks, deletion filtering, and locators. +Historical bodies do not require every historical search index. Rebuild may pause publication, but new content cannot publish +without its required index; retain the usable old index until replacement publication. + +Same-Scope retrieval may select multiple knowledge bases. Cross-Scope helpers authorize each explicit target, call the same +per-Scope API, fuse ranks, and preserve target identity/errors rather than compare incompatible vector-space scores. Reject +unsupported filters/rerank options. Python/MCP use the same service. Reuse Scope read/contribute and Artifact write/governance +permissions, checking every affected object. Acceptance uses 428/412 preconditions, 409 conflicts, 410 deletion, 422 validation, +413 limits, and 503 unavailability. After 202, failures are durable job states rather than conclusions inferred from logs. + +## 9. Implementation and acceptance + +Only plugin storage needs new migrations; existing core tables receive no new fields/migrations. The plugin framework must +provide registration, consumption admission, constrained publication, and visibility checks. Unchanged table schemas do not +mean zero framework adaptation. Generate bindings under the appropriate core or plugin OpenAPI ownership. + +Verify on SQLite, SeekDB, and OceanBase: + +- Multiple knowledge bases per Scope, cross-base authorization, exclusive ownership, and original-only consumption including + recovery scans and manual entry points. +- Build/run, debugging, and Wait Event Markdown from a pinned oceanbase/oceanbase commit; real text-image OCR and provenance. +- Request replay, payload conflicts, active-target conflicts, deduplication, configuration reprocessing, and edit preservation. +- Exit after acceptance, Source registration before acknowledgement, lease recovery, stale tokens, superseding, bounded retries, + and cancellation. +- Prepared output followed by core rollback; core success followed by lost task acknowledgement; old content availability, + invisible uncommitted results, and no duplicate publication. +- Creation/modification/deletion evidence tied to actual revisions; increment on chunk removal, readable zero chunks, history. +- Source/document/knowledge-base deletion racing publication, recoverable cascade, and all ordinary/exact/historical/evidence + read guards. +- Directory/single/batch chunk boundaries, complete index lifecycle, rebuild, and valid-candidate refill. +- OpenDAL snapshots accessible to Server/Worker; later original changes do not change accepted inputs. + +Mocks do not establish real backend/OCR support. Compare the two rules on a small corpus for answer-passage recall, SOP +integrity, and provenance without claiming measured quality or scale in this RFC. #2441 owns ingestion/resources, #2442 owns +queue/processing/publication, #2443 owns retrieval/APIs, and #2444 owns operation/acceptance. No new issues are required. + +# Drawbacks + +The plugin owns migrations, backup, and recovery for three domain tables and indexes. Separate storage requires reconciliation +and short commit gates. Complete chunk snapshots, successful operation evidence, soft deletion, and terminal jobs consume +storage. Resource kinds need explicit constraints. The first phase offers neither distributed transactions nor large-scale +performance guarantees, and index rebuild may affect multiple knowledge bases within a Scope. + +# Rationale and alternatives + +- One business plugin owns membership, work, and configuration, while internal parsers remain independently extensible. +- Three plugin tables provide per-Source deletion and per-file jobs without changing core models. Two fixed resource kinds + avoid separate document-state/receipt tables. +- Sources hold immutable inputs/success evidence; jobs hold mutable execution state. Pending commands are not success Sources. +- Artifacts manage whole-document revisions and chunk rows support exact reads; editing old rows would destroy history. +- An independent queue supports slow parsing/external waits without existing consumption cursors, reusing only separable + Supervisor runtime tools. +- Prepare immutable results, publish core, then acknowledge the job to respect storage isolation; cross-store atomicity is not + a default capability. +- Deletion revisions provide stable operation evidence; head retirement and guards control visibility. Removing search entries + alone cannot delete content. + +# Prior art + +Builds on [plugin interfaces #2549](https://github.com/oceanbase/powercontext/pull/2549), +[plugin APIs #2579](https://github.com/oceanbase/powercontext/pull/2579), +[Source identity](1400_source_definition_and_observation_model.md), +[processing supervision](1515_artifact_processing_supervisor.md), and +[Source/Artifact APIs](1437_source_artifact_rest_api.md). Reuse original identity, Artifact revisions, successful operation +evidence, and governance while implementing independent knowledge-base jobs and chunk projections. Atomic Memory retirement +does not automatically provide Source cascades or plugin lifecycle guards. + +# Unresolved questions + +Before implementation, fix composite registration/constrained writer signatures, backend lock order for publication/deletion +gates, generic read guards, and exclusive Source consumption admission. Implementation fixes OCR models, chunking defaults, +lease/concurrency/retry limits, API count/byte bounds, and concrete schema types without changing ownership or commit semantics. +Restoration/erasure, job archival and idempotency retention, rename identity, per-base vector spaces, and full edited-document +export require separate contracts. + +# Future possibilities + +Word/PDF/scene-image parsers reuse jobs, chunking, publication, and retrieval. External parsing persists a remote reference and +resumes by polling, without requiring a full parser framework initially. Further extensions include OpenDAL providers, rerank, +neighbor/parent-section context, and bounded multi-step retrieval. Their quality and costs require measurement rather than +being prerequisites for the first phase. diff --git a/docs/en/rfcs/2570-rag-knowledge-base.md b/docs/en/rfcs/2570-rag-knowledge-base.md deleted file mode 100644 index 5d5a7fd161..0000000000 --- a/docs/en/rfcs/2570-rag-knowledge-base.md +++ /dev/null @@ -1,519 +0,0 @@ ---- -title: "RFC 2570: Document knowledge bases with rag Artifacts" -description: "OpenDAL ingestion, versioned document chunks, and knowledge-base retrieval using Source journals, shared Workers, and Source lifecycle metadata." ---- - -- Proposal Name: `rag_knowledge_base` -- Start Date: 2026-11-10 -- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) -- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) -- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) - -# Summary - -Provide document knowledge bases through a Source plugin and the `document` and `rag` Artifact families. A Scope -contains multiple user-created rags; each document Source and whole-document Artifact belongs to exactly one rag. -OpenDAL captures immutable originals. Markdown and image OCR share simple chunking. Asynchronous operation requests -are immutable Sources consumed through the existing journal, cursor, and Worker framework. Commit each document -revision, its chunks, lineage, indexes, and consumption cursor atomically. - -Add one document chunk table and generic soft-deletion fields to `pc_sources`. Reuse Artifact storage and processing -schemas without a separate import/task/state platform. Expose content availability rather than durable per-file -execution status. This RFC proposes a contract; it does not describe released functionality. - -# Motivation - -Business descriptions and SOPs need passage retrieval over complete documents, exact provenance, explicit updates, -and predictable deletion. Memory extraction does not preserve every passage. The first phase should cover that -workflow with existing Source/Artifact infrastructure and explicit failure semantics. - -Source snapshots, accepted operation requests, and successful Artifact revisions serve different purposes. Keep -those distinctions without mutable task state in Source payloads. Retrieval is derived from committed chunks and -isolated from Memory indexes and configuration. Reuse requires actual family, read, projection, and Worker integration. - -# Guide-level explanation - -1. Create an empty `rag` through standard Artifact creation in an existing Scope. -2. Select the rag and a local directory/file through the configured OpenDAL Source plugin. -3. View whether a usable document exists: generated, update needed, or not yet generated. No result does not prove failure. -4. Search selected authorized rags. A failed update leaves the previous committed content searchable. -5. Import changed files or explicitly reparse. Parsing restarts from a fixed original and commits a whole new revision. -6. Edit or remove a chunk asynchronously. The request is accepted first; a successful new revision retains old history. - -Users need not supply file hashes, namespaces, or document IDs. Scope remains the authorization boundary. Importing -the same file into two rags creates different logical Sources/documents, with optional physical snapshot deduplication. -Support Markdown and independently imported text images using RapidOCR with ONNX Runtime. Markdown image references -are retained without fetching or OCR. SQLite, SeekDB, and OceanBase must support the workflow, one selected backend -per deployment. - -PDF, Office, plain TXT ingestion, semantic/LLM chunking, complex layout reconstruction, scheduled directory sync, -per-rag embedding spaces, zero-downtime index cutovers, a task-management UI, durable per-file failure details, -restoration/permanent erasure, and large-corpus performance acceptance are outside the first phase. - -# Reference-level explanation - -## 1. Ownership and plugin configuration - -```text -Scope - rag R1 - original Source S1 -> operation Source Q1 (import) -> document D@1 -> chunks - operation Source Q2 (edit D@1) -> document D@2 + successful edit evidence E2 - original Source S2 -> operation Source Q3 (reparse) -> document D@3 - rag R2 - separate original Sources, requests, and documents - -Source plugin: OpenDAL capture, snapshot access, original and trusted operation Source types -Document plugin: Markdown / OCR, chunks, revisions, operation consumption, provenance and chunk index lifecycle -rag plugin: collection configuration and retrieval orchestration over document chunks -Shared facilities: Source/Artifact APIs, Supervisor/Worker, cursor, transactions, database/model adapters -``` - -The three logical plugins may ship in one package. The application service coordinates them; it is not a fourth -plugin. A rag can exist without Sources. Its configuration uses Artifact revisions, and deletion uses head governance. -The knowledge-base Scope enables only document business: document Sources, document Artifacts, and pre-created rag -Artifacts. Operation and edit-evidence Sources are internal records of that same pipeline, not inputs to other families. -Scope admission and consumer bindings enforce this restriction; no new Scope table is required. -There is no rag runtime table. Ownership is explicit in immutable Source payloads and document manifests, not inferred -from tags or evidence lineage. Each original, request, and document has one owner rag. - -The package owns independent embedding/index configuration. Explicit plugin settings win; installation may initialize -compatible missing values from the main path and persist the resolved profile and credential references. Do not copy -secrets into Artifacts or follow subsequent main-path changes. Parser/OCR/chunker configuration may vary by rag; -the initial embedding/index profile is plugin-level, shared by the document family within each Scope. Isolate indexes -by family, definition, and vector-space identity. Model/dimension changes use the existing family rebuild mechanism. - -Only the document pipeline may directly consume document originals; only its operation processor may execute -operation Sources. Enforce eligibility during selection, execution, and commit. Registering a new Source type alone -does not exclude it from existing generic consumers. Requests are neither ordinary generation input nor searchable text. - -## 2. OpenDAL ingestion, identity, and duplicate detection - -Use OpenDAL/`opendalfs` for local listing/reads and immutable snapshots in a managed directory. The plugin instance -must run where the selected path exists. Fix root, relative-path, and symlink normalization; reject escapes. Capture -before acceptance, hash the exact saved bytes, and parse that snapshot, not a later read of a changing file. mtime/size -are hints, not proof of equality. Preserve the first canonical capture metadata when reusing an existing Source. - -The first phase supports only locally accessible directories, using the OpenDAL `fs` backend. The importer, Server, -and Worker must access the same managed snapshot directory, directly or through local container volume mappings. -Check storage configuration/access before accepting processing requests. Store `original_path` for provenance and -`snapshot_ref={store_id, object_key, digest}` for actual reads; resolve the storage alias to each process's configured -local root. Worker reads the captured snapshot even if the user later edits or removes the original file. Remote -client uploads, cross-machine file transfer, object-storage originals, and remote shared storage are outside this phase. - -```text -file_key = (scope_id, rag_id, collection_id, normalized_relative_path) -document_id = stable_hash(identity_version, file_key) -content_digest = SHA256(captured raw bytes) -source_key = stable_hash(source_schema_version, file_key, content_digest) -processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) -index_key = hash(complete embedding inputs, plugin profile and projection versions) -``` - -Derive collection from the registered storage instance/binding and normalized root, not a scan token. Verify full -identity fields on hash matches; never truncate paths or merge documents by digest alone. Original payloads store -owner rag, file identity, original path, document ID, media type, digest, and snapshot reference. The same document ID -is available before an Artifact exists; no reservation row is required. - -| Observation | Required behavior | -| --- | --- | -| Same file/content/processing profile, usable successful result | Reuse Source/document; skip parsing, check index readiness separately | -| Equivalent request still unconsumed | Coalesce when found in the unconsumed journal; racing duplicate imports recheck success before writing | -| Same input, no successful result | An explicit retry may create a new request; a capture checkpoint is not processing success | -| Same path, changed bytes | New original Source, same document ID, whole-document revision on success | -| Parser/OCR/chunker changes | Reuse original Source; explicitly request reprocessing | -| Only embedding/index changes | Reindex committed chunks without OCR | -| Different path/rag, same bytes | Different logical Source/document; optional physical snapshot reuse | -| Unchanged original after manual edits/removal | Preserve the manual revision; do not compare its edited text hash as if it were the original hash | -| Reprocessing an edited document | Require explicit `manual_edits_policy=discard`; otherwise retain current content and reject the conflict | - -Reverting to old bytes can reuse an older Source, so desired input follows the latest accepted import/reprocess request, -not the largest original Source journal position. Finding a Source is not proof that the current document matches it. -Renames create new identities initially; absent files do not imply deletion. Deleted Source identities and retired -document heads must not be silently resurrected. - -Parser/chunker choice is not part of document identity. Explicit reprocessing of the same Source with a new splitting -method keeps the same `document_id` and `rag_id`, and commits the next revision only after content/index preparation -succeeds. It replaces the current effective content/indexes, not historical rows. Failure leaves the old head usable; -manual modifications still require explicit discard authorization. Rechunking may assign new chunk IDs. - -Reuse Source `collect` discovery/add/status/control. A client-generated `scan_token` in plugin input identifies one -explicit scan; retrying that input reuses its collection target. A new explicit scan has a new token but the same -file identities. Scan once per token; do not imply periodic sync or that repeated add restarts a stopped target. -Collection status describes acquisition only. Scans consult successful document results as well as capture checkpoints. - -## 3. Markdown normalization and chunking - -```text -Markdown bytes -> markdown-it-py structure / byte mapping ----+ - +-> rule-based chunks -Image -> RapidOCR text/regions -> normalized Markdown --------+ -``` - -OCR preserves actual text, order, confidence, and original-image regions, including preprocessing transforms. -Normalization escapes Markdown syntax and groups lines/paragraphs; it does not invent headings, use LLM correction, -or reconstruct complex tables. Map normalized spans back to OCR lines and image regions, stating locator precision. -Derived Markdown never replaces the original image Source. - -Use headings, paragraphs, lists, and code blocks. Merge short blocks up to `max_chunk_chars`; split oversized blocks -by sentence/length, optionally using `overlap_chars`. Preserve heading paths, language, and continuation flags. -Overlap must be smaller than the maximum. Example values 1200/100 need validation; actual embedding token limits, -including heading/prefix context, must be enforced without silent truncation. - -Validate formats, UTF-8, image decoding/pixel limits, OCR models, timeouts, and no-text outcomes. Pin/test real RapidOCR, -ONNX, and model versions. Empty OCR is not successful empty-document ingestion. An explicit removal of the last chunk -is allowed. No separate section-tree, parsed-node table, or complete Markdown cache is required. Store bounded source -mappings in chunk metadata; keep vectors out of canonical chunks and full text out of the Artifact manifest. - -## 4. Persistence: one detail table and Source lifecycle fields - -Do not add `pc_document_imports` or `pc_document_source_states`. Source payloads carry immutable identities/requests; -Artifacts carry successful revisions; existing processing tables coordinate consumption. Do not replace the removed -tables with unbounded maps in rag content, Scope settings, checkpoints, or cursors. - -| Reuse | Responsibility and structural change | -| --- | --- | -| `pc_sources` | Originals, operation requests, successful edit evidence; add generic lifecycle fields below | -| Source journal/heads, connector checkpoints | Acceptance order and acquisition progress; unchanged schema | -| `pc_source_cursors` | Document binding's contiguous scan position and CAS generation; unchanged schema | -| Processing intents, leases, binding state | Scope/binding wakeup, invocation generations, execution fences; unchanged schema, not per-file tasks | -| `pc_artifacts`, `pc_artifact_heads` | rag configuration, document manifests, current revision and retirement/governance; unchanged schema | -| Source/Artifact lineage, locators, tags | Original input, request, base revision, successful edit evidence; existing schema | -| Artifact search states/coverage/changes/text/vectors | Current-revision fragment indexes and build coordination; existing facilities plus a chunk projection adapter | - -Add these columns to `pc_sources`: - -| Column | Type/default | Meaning | -| --- | --- | --- | -| `lifecycle_state` | Short string, NOT NULL, default `active` | `active` or `deleted`, one-way transition initially | -| `deleted_at` | Nullable UTC timestamp | First deletion time; repeat deletion does not refresh it | - -Backfill existing Sources as active. Payload, identity, and journal position remain immutable. Lifecycle metadata is -excluded from content hashing. Use row locking/conditional updates and consistent lock ordering against document -commits; no separate Source deletion-generation column is required initially. Adapt add/get/list, evidence and generation -access, and family reads. Duplicate add of a deleted identity must not return usable content or reactivate it. Internal -migration/cascade scans may include deleted rows; public reads cannot bypass deletion. This phase exposes deletion for the knowledge-base pipeline's originals and -internal records only, not unrelated Source types or cross-family cascades. Verify additive migrations on -SQLite, SeekDB, and OceanBase rather than treating Artifact retirement as existing Source soft-deletion support. - -The only new domain table is `pc_document_chunks`: - -| Constraint/fields | Design | -| --- | --- | -| Primary key | `(scope_id, document_id, revision, chunk_id)` | -| Unique order | `(scope_id, document_id, revision, ordinal)` | -| Content | `text`, `content_digest` | -| Structure | Heading path, continuation/overlap metadata | -| Provenance | Normalized spans, original byte/image locators, origin/verbatim, base/edit references | - -Use backend-safe keys and bounded metadata. Each revision is a complete immutable chunk snapshot: removing one of -100 chunks produces a new manifest and 99 rows, preserving the original 100. The existing Artifact envelope identifies -the document/revision; its bounded manifest contains title, owner rag, file identity, root SourceRef, processing -fingerprint, chunk count/digest, manual-change flag, and `applied_request_ref`. A client derives the chunk-directory -route from the exact document reference. Do not embed chunk bodies or an unbounded list of chunk IDs in the manifest. -History uses exact revisions, not today's head. Chunk rows also supply `text_length`, measured in Unicode code points, -for metadata-only directory reads without returning body text. - -Initially, membership and availability may require paginated Scope/type scans and payload decoding plus exact -Artifact reads by deterministic document ID. Do not assume canonical payloads already have queryable JSON owner/path -indexes. Filtered pagination tracks the scan position without losing later matches. Validate ownership and full identity -at writes/reads. These scans have costs; no large-scale performance claim is made. Additional projections require measured -need, not an implicit reintroduction of a task table. - -## 5. Operation Sources, Workers, and transaction boundaries - -A trusted application service creates a dedicated operation Source type, illustrated as `document_operation`; -originals are illustrated as `document_file`. These are plugin registrations, not new storage tables. A request stores -owner rag, document ID, operation, root SourceRef, fixed processing configuration/fingerprint, request ID, base revision, -and bounded edit/discard parameters. Initial import may have no base; edit requires an existing base. Do not store -mutable state, attempts, errors, or a future output revision in its payload. Ordinary user metadata cannot forge commands. - -Import/reprocess regenerates the whole document from a fixed original. Edit supports `replace_text` and `remove`. -Existing `ContentSourceInternal` binds successful `artifact_create`/`artifact_replace` evidence to an exact revision; -it cannot represent an unexecuted command. Preserve that successful-result contract and use the separate request type. - -Accept/reuse the original, insert the request, and call the document binding's `processing_intents.request()` in one -transaction. Only a newly accepted request schedules new work. Extend Source/binding notification integration explicitly; -the current SourceRepository does not automatically discover this proposed processor. - -Request identity is deterministic within Scope/rag/document/operation and client `request_id`. Identical canonical -payload replays return the accepted request; different payload under the same identity conflicts. Replaying a consumed -request never reruns it. An explicit retry uses a new request ID, possibly the same original Source. Incrementing an -invocation counter alone cannot rerun an input already passed by the cursor. - -```text -accept request Source + processing intent atomically - | -existing Worker scans the document binding's journal window in order - | -prepare chunks/embeddings outside the transaction - | -commit document + chunks + lineage + indexes + cursor atomically -``` - -Process sequentially within a Scope/document binding, using bounded windows and existing fences/cursor CAS. Ignore -unrelated Sources while advancing the contiguous scan boundary. No per-file queue or latest-request-wins cancellation -is promised. Requests pin their base; if an earlier operation changes the head, a later request may conflict instead -of silently rebasing. Users refresh and submit a new request. Source acceptance during execution does not mutate the -running request. Scope invocation acknowledgement follows existing `ScopeInvocation` rules; partial work must not -mark an entire window clean. - -The cursor records consumption, including skips, not success. Successful revisions identify their request through -`applied_request_ref` and lineage. There is no durable per-request failure receipt. - -| Outcome | Cursor and recovery | -| --- | --- | -| Input-specific parse/OCR/configuration failure or base conflict | Log sanitized identifiers/error, advance past that request under the execution fence, retain old content, continue other inputs | -| Transient request-local error | Optional bounded in-process retry, then the same failure/skip rule; no durable attempt counter | -| Database failure, index rebuild, or system-wide model unavailability | Do not advance this request; reuse Supervisor backoff/recovery and report binding-level unavailability | -| Process exits before commit | Cursor has not advanced; re-execute the fixed request after recovery | -| Process exits after successful commit | Content and cursor are already committed; do not create another revision | -| Crash between failure logging and skip commit | The request may run again; duplicate diagnostics are allowed | - -Logs follow existing observability contracts and exclude content, credentials, and sensitive paths. Logs are not a -recovery dependency. A consumed failed request requires a new explicit request to retry. Runtime task status or a -request timeout cannot establish permanent failure. - -| Boundary | Work | -| --- | --- | -| Outside transaction | Snapshot capture; parsing/OCR; complete chunk snapshot; embedding and index projection preparation | -| Acceptance transaction | Authorization, ownership/lifecycle/base checks, Source/request acceptance, processing intent | -| Successful content transaction | Recheck Worker/cursor/base/owner/root/index fences; commit manifest, chunks, lineage, successful edit evidence when needed, head, indexes, and cursor | -| Failure-skip transaction | Revalidate execution/cursor fences and advance the contiguous boundary; no document write or successful edit evidence | -| Deletion transaction | Mark Source lifecycle or retire Artifact head; parent/root checks block concurrent publication | - -Models and DDL run outside the content transaction. Chunk projections are prepared from chunks, not full-text JSON -inside the manifest. Validate snapshot and projection fingerprints. New content and indexes become visible together; -failed updates retain the previous head/indexes. During family rebuild defer new document commits, not the generic -content-only path. Rebuild committed chunks without OCR, with explicit unavailability rather than Memory/full-text -fallback or a zero-downtime promise. Verify real transaction behavior on all backends, including SQLite write locking; -ANN limitations need filtered exact retrieval or a clear capability failure. - -The document plugin owns one revision-aware chunk projection boundary used by initial writes, revision replacement, -rebuild, coverage verification, deletion filtering, and retrieval. Rebuild must load the exact committed chunk rows, -not expand the bounded manifest as full text. Coverage compares the manifest count/digest with that revision's chunks -and projections. A zero-chunk revision has valid zero-fragment coverage. Retrieval retains exact document revision -and chunk IDs through scoring/fusion so later chunk reads resolve the actual hit. Generic projection/rebuild code -needs this integration; adapting only the initial write path is insufficient. The rag service reuses these projections -without changing generic Artifact search result contracts. - -## 6. Editing, chunk removal, and deletion - -Validate edit `If-Match` both at acceptance and commit. A successful edit writes a whole new snapshot. Unchanged chunks -keep logical IDs; rechunking assigns new ones; citations always include revision. Removing the last chunk leaves a -readable zero-chunk manifest and no current index fragments. No removal physically deletes old chunk rows. - -At success, create a system Content Source with `role=lineage_only`, `operation=artifact_replace`, and the exact new -revision, recording request/base/root provenance. Preserve the original Source dependency explicitly. Mark edited -text `origin=manual_edit`, `verbatim=false`; old image coordinates are edit evidence, not verbatim proof. Removal -also counts as manual modification. Explicit reparse must authorize discarding manual changes. Unchanged complete -embedding inputs may reuse computation, but index mappings must identify the new current revision. - -| Delete operation | Behavior | -| --- | --- | -| Original Source | Set Source lifecycle deleted; retire a document still rooted in it and revoke dependent history. A revision fully reparsed from another root survives | -| Document | Retire its head; block all revisions/chunks and future commands, leaving original Sources active | -| rag | Retire its head, immediately block all owned content, then recoverably mark all owned Sources (including requests/edit evidence) and document heads deleted/retired | -| Chunk | Commit a new revision without that chunk, retaining history | - -Reuse Artifact `lifecycle_state=retired` and governance CAS. Original Source payloads/snapshots and historical business -content remain stored; user files are untouched. No restore or permanent erase initially. An imported file without a -head is deleted through its original Source; document DELETE returns not found rather than manufacturing a placeholder -Artifact. A deleted pending replacement Source must not retire an older committed version based on a different root. - -Check owner rag, document head, and the exact revision's root on search and generic/exact/history/chunk reads. -Historical base links do not transitively revoke a full reparse from a replacement root. Original Source reads check -its state/owner; deleting just a document does not hide its original. Request/edit evidence reads also check the target -document to prevent retained manual text from bypassing deletion. Deleting a request blocks unconsumed execution, -not an already committed edit: content validity is governed by root/document/rag, not a retroactive cancellation. - -Generic retirement alone may still allow exact reads; add family guards. Large rag cascades rediscover remaining work -from the retired parent and immutable ownership, including deleted rows internally, without a cascade job table. -Exclude invalid rows before ranking even while fan-out is incomplete. Derived indexes retain existing replacement, -removal, and rebuild semantics; preserving business history does not promise every historical index entry stays intact. - -## 7. Availability, Artifact APIs, and chunk access - -| Display | Derivation | -| --- | --- | -| Generated | A usable committed revision matches the selected original/configuration; valid manual changes are preserved | -| Update needed | A usable older revision exists but desired original/configuration differs; it may still be searchable | -| Not yet generated | Source accepted, no usable successful revision; could be unstarted, running, or failed | -| Deleted | Source or owning Artifact lifecycle invalid; no retained text, normally excluded from lists | - -Desired input uses the latest accepted import/reprocess request, or the accepted original if none exists. Manual edits -are not raw-file mismatches. Rag configuration changes affect future requests and may indicate reprocessing is needed; -they do not automatically enqueue it. Do not expose per-file stages, percentages, attempt counts, durable errors, or -infer success from collection completion/cursor advancement. Binding diagnostics and index availability stay separate. - -Reuse existing permissions, errors, references, pagination, ETags, and SDK/MCP operations. Implement necessary contract -changes in `openapi/powercontext.yaml` and regenerate bindings. The current generic create-Source accepts built-in -content; document files go through the Source plugin protocol. Let `R=/v1/scopes/{s}/artifacts/rag/{r}` and -`D=/v1/scopes/{s}/artifacts/document/{d}`. - -| Operation | Existing route or necessary extension | -| --- | --- | -| Create/configure rag | Existing POST `/v1/scopes/{s}/artifacts`, GET/PUT `R`, revisions/tags; full replacement and existing preconditions | -| Import/control | Existing POST `/v1/source-management/add`, collect capability/instance, existing status/target/instance controls | -| List files and available results | Existing Source list/get and Artifact list/get/history, validated owner-rag filters, helper join by document ID; no `R/processing` task list | -| Explicit reparse | POST `D/processing`, `source_ref`, `action=reprocess`, `request_id`, optional configuration/discard; 202 request acceptance | -| Edit/remove chunk | POST `D/edits`, current `If-Match`, typed bounded operation and request ID; 202 request acceptance | -| Get document | Existing Artifact GET/history; title, exact revision, owner, chunk count and original reference, no chunk bodies | -| Chunk directory | GET `D/revisions/{rev}/chunks`; paginated ID/order/heading-path/text-length metadata only | -| Get one chunk | GET `D/revisions/{rev}/chunks/{chunk_id}`; body, provenance and manual-edit markers | -| Get chunks in a batch | POST `D/revisions/{rev}/chunks/batch-get`; bodies for an explicit bounded list of chunk IDs | -| Knowledge-base retrieval | New POST `/v1/scopes/{s}/rag/retrieve`; explicit `rag_ids`, query/mode/limit, chunk-reference results | -| Soft-delete | DELETE on existing exact Source/Artifact routes; Artifact governance `expected_generation`, one-way Source lifecycle | - -Reparse with an existing head requires `If-Match`; without a head, use the deterministic document ID and -`If-None-Match: *`. Validate that Source ownership/file identity resolves to that ID, and recheck the base at execution. -Do not return Scope invocation generations as document target generations. Reuse `scope.contribute` for document -operations and `scope.admin` for rag/Source deletion, with existing read authorization. - -Create rag: - -```json -{"family":"rag","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} -``` - -Directory collection; capability/instance names are illustrative deployment-discovered values: - -```json -{"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} -``` - -Remove a chunk with POST `D/edits` and the current document ETag: - -```json -{"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} -``` - -The 202 receipt states durable acceptance, not pending status or a future revision: - -```json -{"accepted":true,"document_id":"doc-1","request_source":{"source_type":"document_operation","source_id":"request-03"},"current_revision_at_accept":2} -``` - -`current_revision_at_accept` is an observation, not the output. Confirm success through a revision's -`applied_request_ref`; no matching revision does not prove failure. For a new execution, refresh preconditions and -use a new request ID. Identical replay returns the original acceptance fact, not a fresh execution result. - -Explicit reparse, with `If-Match` for an existing document and authorization to discard manual changes: - -```json -{"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} -``` - -Document GET and exact history retain the existing Artifact envelope with the bounded manifest. The directory -returns `items/next_cursor`, ordered by ordinal, with no body or excerpt. Its cursor binds Scope/document/revision; -concurrent head changes cannot mix revisions. Single and batch reads use that same exact revision, never today's head. -All three routes enforce owner/document/root lifecycle checks, including historical reads. A zero-chunk revision has -an empty directory. Single-item output includes text, source reference/locator, origin/verbatim and edit provenance. - -Batch-get accepts a nonempty unique `chunk_ids` list, returns items in request order, and does not accept mixed -revisions. Enforce configured ID-count and response-byte limits; reject oversized batches without truncating text. -Authorize the parent first, then validate every ID in that revision. A missing ID fails the batch with 404 rather -than silently omitting it; deleted resources follow the existing authorized 410 rule. These are read operations, -not a general bulk mutation API. - -Example directory response for one exact revision: - -```json -{"document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} -``` - -Batch request to POST `D/revisions/2/chunks/batch-get`: - -```json -{"chunk_ids":["chunk-1","chunk-2"]} -``` - -Knowledge-base retrieval uses POST `/v1/scopes/{s}/rag/retrieve`, not the generic Artifact search response: - -```json -{"rag_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} -``` - -Return bounded chunk hits with rag ID, exact document reference, chunk ID, score, and source locator; optional snippets -are bounded and do not replace the full-body chunk API. Here `limit` counts chunk hits. For example: - -```json -{"hits":[{"rag_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} -``` - -The generic Artifact GET/history and search contracts remain intact: Artifact searches return Artifacts, not arbitrary -chunks or another family's documents. A document-specific internal handler can reuse index/model facilities; the -separate rag retrieval route avoids adding knowledge-base matches to every generic search item. Require nonempty -validated rag selection and filter ownership/lifecycle before ranking. Unsupported filters/rerank options fail clearly. -Cross-Scope helpers authorize explicit `(scope, rag)` targets, call the same per-Scope rag retrieval route, rank-fuse, -and retain target errors/identities. Do not compare incompatible raw scores. HTTP, Python and MCP expose equivalent -metadata, chunk-read and retrieval operations, reusing common authorization and errors. - -At acceptance use existing 428/412 preconditions, 409 payload/discard conflicts, authorized 410 deletion, 422 validation -(or transport 413), and 503 service unavailability with the existing `error.code/message/details` envelope. After 202, -request-local failures/conflicts follow the log-and-consume rule; there is no durable error-status endpoint. - -## 8. Implementation and acceptance - -Reuse requires Source lifecycle migrations/read guards, trusted request admission, consumer eligibility, document -binding notification, journal selection/cursor transactions, chunk projection, and ownership filtering before top-k. -It does not imply a zero-change framework or existing support for all proposed routes. - -Run the same public workflow against SQLite, SeekDB, and OceanBase: - -- Multiple rags and Scopes, exclusive file ownership, authorized selection and no cross-rag results. -- Markdown from a pinned `oceanbase/oceanbase` commit and real OCR fixtures with accurate provenance. -- Source migration backfill, immutable payload, deleted replay rejection, and exact/history/evidence read guards. -- Successful duplicate skipping, failed-input retry with a new request, configuration reparse, embedding-only rebuild. -- Atomic request/intent admission, restart recovery, atomic content/cursor commit, no rerun on request replay. -- Input-local failure consumption versus system-wide failure retention; cursor advancement never means file success. -- Async base conflicts/late Workers, no successful edit evidence on failure, manual-edit protection. -- Versioned chunk removal including the last chunk, complete history and correct current indexes. -- Source/document/rag deletion races, recoverable cascade, replacement-root independence. -- Independent plugin configuration, index isolation, rebuild unavailability, pagination, contract generation and SDK/MCP parity. -- Metadata-only document/directory reads, exact-revision single/batch chunk bodies, byte/count bounds and missing-ID behavior. -- Same-Source rechunking keeps document/rag identity while replacing the current revision and retaining history. -- Chunk projection/rebuild/coverage parity, including zero chunks and exact retrieval-hit resolution. -- Local OpenDAL snapshots accessible to importer/Worker, including container mappings; no remote-path acceptance. - -Mocks do not establish real backend/OCR support. Use #2441 for ingestion/ownership/Source lifecycle, #2442 for processing, -requests/chunks/atomic writes, #2443 for retrieval/interfaces, and #2444 for diagnostics/acceptance. One implementation -branch/PR may deliver these stages. This RFC does not close implementation issues or establish large-corpus capacity. - -# Drawbacks - -Operation Sources grow the journal; complete chunk snapshots and retained deleted data consume storage. Sequential -consumption can cause head-of-line waiting. Availability lacks durable per-request failures, and initial owner/request -filtering may scan payloads. Family rebuilds can interrupt several rags. These are explicit first-phase tradeoffs; -Source lifecycle and consumer/projection integration still require meaningful implementation work. - -# Rationale and alternatives - -- Multiple rag Artifacts preserve project-level Scopes without coupling collections to authorization. -- Source journals persist accepted operations without a new mutable task table; in-memory-only commands lose work on restart. -- Request Sources preserve intent; exact successful edit Sources preserve results. Reusing the latter before success misstates provenance. -- Source lifecycle columns express generic deletion while payloads remain immutable; a document-only state sidecar duplicates this responsibility. -- Whole-document manifests plus chunk rows avoid giant content JSON and per-chunk Artifact identities. -- Immutable revision replacement preserves old counts/digests/citations; direct chunk deletion does not. -- Separate task/publication systems could provide richer status/cutovers, but are outside the accepted scope. - -# Prior art - -Build on [Source plugins](2012-source-plugin-system.md), [Artifact plugins](2175-artifact-plugin-system.md), -[Source identity](1400_source_definition_and_observation_model.md), [processing supervision](1515_artifact_processing_supervisor.md), -and [Source/Artifact APIs](1437_source_artifact_rest_api.md). Existing OpenDAL hashing, Source cursor CAS, Artifact -head governance, and fragment indexes provide foundations, not a complete knowledge-base implementation. Existing -Atomic Memory retirement is not already a Source-to-document cascade contract. - -# Unresolved questions - -Fix exact Source/capability signatures, supported image/model versions, limits/chunker defaults, bounded retry error -classification, and backend migration/index transaction behavior during implementation. Additional query projections -must be justified by measured costs. Durable per-request outcomes, restore/erasure/GC, rename identity, per-rag vector -spaces, and full edited-Markdown export need separate contracts; overlapping chunks cannot simply reconstruct a full edit. - -# Future possibilities - -Extend OpenDAL providers, parsers, chunkers, rerankers, and bounded agentic retrieval through component boundaries. -Measure before adding shared immutable chunk bodies, richer task state, or collection-scale projections. None is -required for the first phase's ownership, recoverable requests, versioned content, and exact evidence. diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md new file mode 100644 index 0000000000..323df8dd6a --- /dev/null +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -0,0 +1,397 @@ +--- +title: "RFC 2570:Knowledge Base 文档知识库插件" +description: "以单个业务插件、独立持久任务队列和三张插件业务表提供文档知识库,不改变已有 Source/Artifact 表结构。" +--- + +- Proposal Name: `knowledge_base_plugin` +- Start Date: 2026-11-10 +- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) +- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) +- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) + +# 概述 + +以一个 `knowledge-base` 业务插件提供本地文档接入、解析切块、版本管理和混合检索。一个 Scope 内可以预创建多个 +`knowledge-base` Artifact;原文 Source 和整篇 `document` Artifact 各自独占归属一个知识库。复用现有 Source、Artifact、 +head 和 lineage 表,不改变它们的结构;插件新增资源登记、独立任务和 chunk 三张业务表。后台处理不使用原有 Source +消费 cursor。本文是目标设计,依赖插件框架扩展,不表示功能已经发布。 + +# 动机 + +业务说明和 SOP 需要原文保真、片段检索、可预测更新与删除。解析可能较慢或依赖外部服务,需要持久任务和逐文件失败恢复。 +业务插件应独立管理这些状态,不把知识库字段加入共享 Source 模型,也不通过一个顺序消费 cursor 阻塞其他文件。 +Artifact 继续管理整篇文档版本;chunk 明细与索引分离,避免读取大型正文 JSON。 + +# 使用层说明 + +1. 通过通用 Artifact API 创建空 `knowledge-base`,再选择本地目录/文件导入。 +2. 导入返回持久任务 ID;界面可以显示排队、处理阶段、失败原因、完成结果及当前可用版本,不要求百分比。 +3. Markdown 和独立文字图片分别经过 Markdown 解析和 RapidOCR,统一切块、建立全文/向量索引后发布 document。 +4. 原文件变化或显式重新解析沿用 document ID,成功后发布新 revision;失败继续使用旧版本。 +5. 手动编辑或移除 chunk 也生成新 document revision,保留历史。检索可选择同一 Scope 内多个知识库。 +6. 删除只改变逻辑可见性,保留业务正文、原文快照和历史;普通、精确、历史、证据和检索入口均遵守删除规则。 + +首期覆盖 SQLite、SeekDB、OceanBase,支持本地 OpenDAL fs、Markdown、RapidOCR + ONNX Runtime、规则切块和人工编辑。 +Markdown 内图片保留引用,不自动抓取或 OCR。不要求几万篇规模测试。PDF/Office、场景图理解、远端上传/原文存储、 +定时目录同步、语义/LLM 切块、恢复/永久擦除、逐知识库 embedding 空间和无停机索引切换不在首期范围。 +任务状态接口属于首期;完整管理页面可以在相同契约上实现,不以调度效果图作为已实现能力。 + +# 参考层说明 + +## 1. 一个业务插件与命名 + +插件统一注册专用文档 Source 类型、`knowledge-base`/`document` family、后台任务入口、自有存储迁移和 API。 +接入、解析、切块、检索是内部模块,不拆成独立安装的插件。方案依赖 [#2549](https://github.com/oceanbase/powercontext/pull/2549) +和 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 后续提供所需的复合能力注册、受限写入和 API 扩展;不把提案当作已发布接口。 + +| 位置 | 标识 | +| --- | --- | +| 展示名 | Knowledge Base/知识库 | +| 插件与知识库 family | knowledge-base | +| 整篇文档 family | document | +| 归属/跨库选择字段 | knowledge_base_id/knowledge_base_ids | +| 模块与配置前缀 | knowledge_base | +| 插件表前缀 | pc_knowledge_base_ | + +```mermaid +flowchart TD + S[Scope] --> K1[knowledge-base K1] + S --> K2[knowledge-base K2] + K1 --> R[资源登记: 稳定文件身份] + R --> O[不可变原文 Source] + R --> J[独立 job] + O --> P[解析与规则切块] + J --> P + P --> C[不可变 chunk 结果与索引] + C --> D[document revision: 有界 manifest] + E[lineage_only 操作证据] --> D + D --> Q[知识库检索与精确 chunk 读取] +``` + +Scope 保持授权边界。知识库 Scope 的业务内容只包括文档 Source、document 和 knowledge-base;操作证据是内部记录。 +所有归属都显式保存并核验,不从 tags 或 lineage 推断。文档原文只供 document 管线处理;原文不是 lineage_only。 +框架的消费准入必须覆盖写入通知、启动恢复扫描、自动消费和手动生成,不能只靠 Source 类型名称或不发送唤醒来隔离。 +同库部署依赖这些通用扩展点,不默认另建 PC Server;尚未实现准入之前不能宣称隔离有效。 + +插件独立持有 embedding/索引配置,可在安装时从兼容主路径初始化,此后不自动跟随。密钥保持在部署配置中。 +首期同一 Scope 的 document 共用插件 profile,解析/切块可按知识库配置;模型和索引配置固定进任务及结果元数据。 + +## 2. OpenDAL、身份与去重 + +首期只接受插件运行环境可访问的本地目录。导入进程、Server 和 Worker 通过相同存储别名访问受管不可变快照目录, +可使用本机容器卷映射。OpenDAL fs 提供本地读取,不会让远端客户端路径自动可访问。拒绝根目录越界,固定符号链接策略。 + +Source 记录 `original_path` 作为出处,`snapshot_ref` 包含 store_id、object_key 和 digest。先保存快照并对实际字节计算 +SHA256,再持久接受任务;解析只读快照,不读可能已变化的原文件。mtime/size 只用于提示,不能代替内容 hash。 + +```text +file_key = (scope_id, knowledge_base_id, collection_id, normalized_relative_path) +document_id = stable_hash(identity_version, file_key) +source_key = stable_hash(source_schema_version, file_key, raw_content_digest) +processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) +index_key = hash(complete embedding inputs, plugin profile and projection versions) +``` + +Collection 从存储实例和规范化根目录派生,与本次扫描/任务 ID 无关。核对完整身份以处理摘要碰撞,不截断路径。 +Source payload 固定归属、document ID、文件身份、media type、摘要和快照;重放不重写采集时间等 canonical 信息。 + +| 情况 | 行为 | +| --- | --- | +| 同请求键、同参数 | 返回同一任务/确定结果;同键不同参数返回冲突 | +| 同文件字节/配置且有可用结果 | 复用 Source/document,检查索引是否可用,不重复解析 | +| 不同请求键命中相同活跃目标 | 返回 409 和已有任务引用,不创建重复执行 | +| 原文字节变化 | 新 Source,同 document ID,新目标代次和任务 | +| 显式重解析/切块配置变化 | 复用 Source 与 document ID,成功发布新 revision | +| 仅 embedding/索引变化 | 从已提交 chunks 重建,不重复 OCR | +| 同字节不同路径/知识库 | 不同逻辑 Source/document,可共享物理快照 | +| 存在人工编辑 | 普通重复导入保留编辑;重新解析必须明确 manual_edits_policy=discard | + +Source 已存在不等于处理成功。文件回到旧字节可引用较早 Source,期望输入以资源登记中的最新目标为准,不以 journal 顺序为准。 +改名首期视作新文件,目录消失不自动删除;已删除身份不因重导入静默恢复。显式 reprocess 不因结果相同而当作普通导入跳过。 + +## 3. 轻量解析与切块 + +解析器入口只需接受快照引用和固定配置,输出 Markdown、来源定位及可选警告。内部格式注册表选择 Markdown 或图片解析器; +后续格式增加解析器和测试样本即可,不要求通用文档 AST、解析器能力协商或独立解析插件系统。 +解析器不写 Artifact、任务状态或索引;外部服务适配可以返回待完成引用,由任务执行层保存并继续。 + +Markdown 使用 markdown-it-py 提取结构和来源映射。图片使用 RapidOCR + ONNX Runtime,保留文本框、顺序、置信度及预处理坐标变换, +整理成 Markdown,但不猜测复杂标题、表格或流程图语义。规范化文本位置映射回原图,声明定位精度;派生 Markdown 不替换原文 Source。 + +- 默认按标题/内容块组织,再对超长块递归切分;缺少可靠标题时按段落/句子递归切分。 +- 代码、表格和列表步骤尽量完整;超长表格按行拆分并保留表头,超长代码保留语言和续块标记,仍受硬上限限制。 +- Overlap 用于拆开的长段落,不机械跨章节重叠;中文使用句号/分号等边界。 +- 保存标题路径和原文定位;embedding 输入包含标题时,按完整输入检查模型 token 上限,不能把字符数等同于 token 或静默截断。 +- 参数包含 max_chunk_chars、overlap_chars;1200/100 仅为待验证示例,不是质量结论。 +- 校验 UTF-8、图片解码/像素上限、模型版本和资源限制;OCR 无文字显式失败,不伪装成功空文档。 + +规则保持确定、可测试。修改切块配置可复用可验证的解析结果;不要求首期建立复杂阶段缓存。 + +## 4. 持久化与关系 + +### 4.1 现有表原样复用 + +| 表 | 职责 | +| --- | --- | +| pc_sources | 不可变原文引用、成功人工/删除操作的 lineage_only 证据;不增加列 | +| pc_artifacts | knowledge-base 配置、document manifest、不可变 revision | +| pc_artifact_heads | 当前 revision、lifecycle_state、governance_generation | +| pc_artifact_lineage_sources/pc_artifact_lineage_artifacts | 精确版本的输入/操作证据和 base 引用 | +| 既有权限、tags 和引用设施 | 复用公共语义,不承载无界任务或成员 JSON | + +原有 processing intents、cursor、lease、binding state 表不用于本插件任务,不增加知识库字段或记录。 +Source journal 可保留为原有持久化约束的一部分,但不驱动知识库任务发现或完成。 + +### 4.2 三张插件业务表 + +表属于插件专属存储,由插件迁移;复用 SQLite/SeekDB/OceanBase 连接和适配能力。全文/向量辅助结构不计入业务表数。 + +| 表 | 关键字段与约束 | +| --- | --- | +| pc_knowledge_base_resources | scope_id、knowledge_base_id、resource_kind、resource_key、document_id、source_ref、identity_payload、lifecycle_state、deleted_at、target_generation、current_job_id | +| pc_knowledge_base_jobs | job_id、scope_id、knowledge_base_id、document_id、operation、idempotency_key、request_digest、input_snapshot、target_generation、base_revision、state、stage、attempt、next_run_at、execution_token、lease_owner、lease_expires_at、error_code/summary、external_task_ref、result_id、result_revision、result_kind、parent_job_id、checkpoint、cleanup_cursor | +| pc_knowledge_base_chunks | scope_id、knowledge_base_id、document_id、result_id、chunk_id、ordinal、text、text_length、content_digest、heading_path、source_locator、origin、edit_metadata | + +Resources 只支持两类固定记录,不是通用对象平台: + +- `document`:每个稳定逻辑文件一行,首次解析前创建;保存路径身份、当前目标和删除标记,不要求提前创建空 document Artifact。 +- `source`:每个原文 Source 一行,保存归属及独立删除标记;不把所有版本塞进一行 JSON。成功操作证据由其目标 Artifact 的可见性控制。 + +主键为 `(scope_id, knowledge_base_id, resource_kind, resource_key)`。Document key 来自 file_key,Source key 包含完整 SourceRef 身份摘要; +保存并比较完整身份,校验同一 Source 不跨库归属。SourceRef 必须包含 source_type 和 source_id。仅 document 行使用目标代次/当前任务字段。 +资源删除是单向标记;已发布 revision 只读 Artifact head,不再复制一个发布指针。公共时间字段和有界错误/JSON 的存储类型由实现固定。 + +Jobs 对 `(scope_id, knowledge_base_id, operation, idempotency_key)` 建唯一约束,请求摘要覆盖全部业务参数和前置条件。 +索引覆盖到期任务、过期租约、document 和知识库归属。目标行串行化同文档请求,不依赖跨后端不一致的条件唯一索引。 +终态任务保留幂等回执;不另建回执/attempt 表,有限错误和 attempt 计数足够首期展示。 + +Chunks 主键为 `(scope_id, knowledge_base_id, document_id, result_id, chunk_id)`,同结果 ordinal 唯一。 +`result_id` 在 core 分配实际 revision 前标识不可变结果,不能猜测下一个 revision 后写入。 +完整结果保存独立分块快照,向量属于派生索引。`text_length` 为 Unicode 码点数量。 + +Document manifest 有界保存标题、knowledge_base_id、文件身份、root SourceRef、result_id、chunk 数量/摘要、处理/索引指纹、 +人工修改标记、applied_job_id 及必要操作摘要,不嵌入正文或无界 chunk ID 列表。精确 revision 通过 manifest 找结果;历史不依赖当前索引。 + +## 5. 独立队列与状态机 + +```mermaid +stateDiagram-v2 + [*] --> queued + queued --> running + running --> succeeded + running --> retry_wait + retry_wait --> running + running --> waiting_external + waiting_external --> queued + running --> failed + queued --> cancelled + running --> cancelled + waiting_external --> cancelled + retry_wait --> cancelled + queued --> superseded + running --> superseded + waiting_external --> superseded + retry_wait --> superseded +``` + +`stage` 与状态独立:ingest、parse、chunk、index、publish、cleanup。等待外部服务的任务保存远端引用/next_run_at 后释放 Worker; +到期查询继续,不长期持有进程或事务。远端提交使用稳定幂等键;服务不支持幂等时需对账,不能承诺外部调用恰好一次。 + +KnowledgeBaseTaskSupervisor 只扫描插件 jobs,负责领取、心跳、过期回收和确认。可复用已有进程启动/终止、预算和关闭工具; +不接入原有 Scope/binding discovery、intent 或 Source cursor。若现有 Supervisor 与这些机制耦合,则实现轻量插件调度器, +不为复用而把逐文件任务塞回旧表。每个 document 串行发布,不同文档有界并发。 + +`target_generation` 表示用户期望哪个结果,`execution_token` 表示同一任务哪次执行拥有资格。领取、续租和状态更新均条件校验 token; +新目标使旧目标 superseded,租约恢复更换 token。SQLite 使用实际支持的事务/CAS,不假设所有后端均支持 SKIP LOCKED。 + +同键重放在授权及生命周期检查后先识别已接受任务,再检查新请求的当前 base,避免成功重试被旧 ETag 拒绝。 +终态任务不复活;自动有限重试属于同一任务,用户重新执行失败任务使用新幂等键创建新 job。取消不回滚已发布结果。 +编辑/移除固定 base,有冲突的活跃变更时拒绝,不静默排队或换基准。逐文件失败不阻塞整个 Scope。 + +## 6. 接受、发布与跨存储恢复 + +Core 与插件专属存储不共享事务,不能声称 Source、任务、chunk、索引和 Artifact 一次原子提交。 + +| 边界 | 行为与恢复 | +| --- | --- | +| 快照 | 保存不可变原文字节;未接受的孤立快照不是可见内容,永久清理另定 | +| 插件接受事务 | 校验/锁定资源目标,幂等检查,保存固定输入与任务;202 后任务可恢复 | +| Source 登记 | Worker 在 ingest 阶段幂等保存/复用 Source;Source 写成功而任务未确认时可重试,不漏任务 | +| 事务外计算 | 固定快照与配置,解析/OCR/切块/embedding,不持有数据库锁 | +| 插件结果准备 | 保存不可变 result_id 对应的完整 chunks 和可用索引,核对数量及摘要,未被 manifest 引用的结果不可见 | +| Core 发布短事务 | 校验 base、归属和执行资格;提交 document revision、必要操作证据 Source、lineage 和 head | +| 插件完成事务 | 写实际 result_revision 和 succeeded;若确认丢失,按 applied_job_id/result_id 对账,不重复发布 | + +发布、删除、换目标、取消和租约回收必须共享提交资格闸门。短发布期间,插件锁定/校验相关资源与任务记录并保持到 core 提交结束, +同时通过受限 writer 校验知识库 head、document base 和生命周期。锁顺序固定,不在闸门内做模型调用、索引构建或 DDL。 +不能先释放插件锁再仅凭 core revision CAS 发布,否则旧 token/已删除 Source 仍可能提交。 +父知识库删除还须与发布的父状态检查互斥,不能只在任务开始检查。 + +Core 成功后插件事务失败,恢复者先查 manifest/lineage 的确定结果;在改变目标或取消前也做对账,不能把已发布成功记为取消。 +准备好的结果永久不可原地覆盖;重新计算不同内容使用新 result_id。发布失败保留旧 head 和旧结果的可检索索引。 +首期在三种后端验证这些短事务与锁的顺序;不引入分布式事务,也不伪装跨库原子性。 + +## 7. 操作证据、编辑与软删除 + +成功创建/修改/删除 Artifact 需要对应的系统 `lineage_only` Source,关联实际输出 revision,不能用排队请求冒充成功证据。 +复用既有创建/替换证据语义;删除/移除的具体动作及原因保存在有界操作摘要中,不擅自假设核心已有新的 operation 枚举。 +任务是意图与执行记录,操作 Source 是成功事实,两者通过 job/operation ID 关联。 + +| 操作 | 版本和可见性 | +| --- | --- | +| 创建/配置 knowledge-base | 创建或新增配置 revision,关联操作证据 | +| 解析/重解析 document | 同 document ID 发布新 revision,lineage 关联原文;人工触发的变更保留操作证据 | +| 编辑 chunk/移除 chunk | document revision +1,完整新结果;关联成功操作证据,旧行不删 | +| 删除 document/knowledge-base | 新增含有界删除摘要的删除 revision,并在同一个 core 事务 retire head;关联删除证据 | +| 删除原文 Source | 标记 source 资源;取消依赖任务,当前 document 仍依赖它时执行可恢复的 document 删除并生成证据 | + +删除整个 Artifact 生成 revision 是本插件的业务约定,不改变其他 family 的治理规则。删除 revision 可复用之前的 result_id, +无需复制 chunk 正文。操作摘要必须使删除 revision 真正写入,不能被“相同 content 的 put 是 no-op”跳过。 +证据、lineage、revision、head 在 core 同事务提交;失败不产生成功证据。同一已接受操作重放不增加 revision。 + +手动替换文字可保留逻辑 chunk ID,但引用必须带 revision;重切块可产生新 ID。人工正文标记非原文逐字引用,保留原始定位与编辑依据。 +移除最后一块允许零 chunk 结果,当前检索无命中。重复导入不得覆盖人工修改,显式重新解析需要 discard 授权。 + +删除 knowledge-base 先提交父对象删除 revision/retirement,立即阻断全部子内容;接受的 cleanup job 可在进程重启后继续, +分批标记 Source、删除 document、取消处理任务。每个真正变化的 Artifact 生成自己的证据,使用共同 operation ID 关联级联。 +Cleanup 是已删除父对象下的允许操作,不能被普通处理任务的父状态检查取消。已接受清理任务的固定游标只用于插件分批操作。接受删除时先持久保存删除/清理 job,再退休父对象,避免丢失级联工作。 + +删除 document 保留原文 Source 可读;原文读取不因 document 单独删除而失效。删除未发布替代 Source 保留基于其他原文的旧版本。 +S1 对应旧 revision、S2 对应完整新解析时,删除 S1 不删除仅依赖 S2 的当前版本,但依赖 S1 的历史读取失效。 +资源标记与 Artifact retirement 可分阶段完成,读取必须同时检查适用的父对象、document、精确 root 和 Source 标记,不能等待索引清理。 +通用 Source、Artifact 精确/历史和证据读取需要框架可见性扩展点;仅插件检索过滤不满足删除契约。归属登记缺失时拒绝读取,不回退为无约束内容。 +受控内部恢复可以读取 retired 历史以对账;授权管理入口可查看删除后清理任务的有限状态,不开放正文或公共绕过参数。 + +## 8. 接口与检索 + +复用 Source 编码/身份/校验、Artifact CRUD/history/tags、认证、权限、ETag、分页、引用与错误封装。 +文件导入使用插件 Source 接受能力,不能直接调用会触发旧消费者的写入路径。耗时编辑经插件任务接口返回 202; +不把同步 Artifact PUT 悄悄改成异步成功。通用写入不得绕过任务、版本、证据和删除规则。 + +路由为建议契约,插件 API 挂载遵循 #2579,实际注册语法随框架实现固定: +`P=/v1/plugins/knowledge-base/api/scopes/{s}`,`D=/v1/scopes/{s}/artifacts/document/{d}`。 + +| 操作 | 接口/返回 | +| --- | --- | +| 创建知识库 | POST `/v1/scopes/{s}/artifacts`,family=knowledge-base | +| 知识库/document 概览与历史 | 通用 Artifact GET/revisions,返回有界 manifest | +| 导入本地文件/目录 | POST `P/imports`,显式 knowledge_base_id、root/paths 和 idempotency_key;202 任务回执 | +| 重解析/编辑/删除/清理 | POST `P/jobs`,类型化 operation、固定目标和前置条件;cleanup 仅供内部使用,同一业务服务负责现有同步删除/治理入口 | +| 任务列表/详情 | GET `P/jobs`、GET `P/jobs/{job_id}`,分页、阶段、状态、有界错误、成功 revision | +| 取消 | POST `P/jobs/{job_id}/cancel`,仅未发布非终态工作 | +| chunk 目录 | GET `P/documents/{d}/revisions/{rev}/chunks`,分页元数据,不含正文 | +| 单个 chunk | 上述路径追加 `/{chunk_id}`,正文、出处、人工修改信息 | +| 批量 chunk | 上述路径追加 `/batch-get`,POST 有界 chunk_ids | +| 混合检索 | POST `P/retrieve`,knowledge_base_ids、query、mode、limit,返回 chunk 命中 | + +插件 chunk 路由使用与 Artifact 相同的 document ID/revision。路径从通用 Artifact 路由中分离,读取语义仍是精确 revision, +通过该 revision 的 manifest 解析 result_id,不回退当前 head。Directory cursor 绑定 Scope/document/revision,按 ordinal 排序。 +Batch-get 要求非空、无重复 ID,按请求顺序返回;先授权父对象,任一 ID 不存在则整批 404。限制 ID 数量及响应字节数,超限拒绝, +不截断正文。已删除对象授权后返回 410,零块版本目录为空。 + +创建知识库: + +```json +{"family":"knowledge-base","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +``` + +导入,目录任务产生有界批次的逐文件子任务,parent_job_id 关联;目录完成只表示枚举/子任务接受结束,不等于全部文件处理成功: + +```json +{"knowledge_base_id":"ops","root":"/work/docs","idempotency_key":"import-01"} +``` + +移除 chunk,已有 document 使用当前 If-Match;首次生成使用明确的无 head 前置条件,不猜未来 revision: + +```json +{"knowledge_base_id":"ops","document_id":"doc-1","operation":"remove_chunk","idempotency_key":"edit-03","base_revision":2,"input":{"chunk_id":"chunk-3"}} +``` + +```json +{"job_id":"job-03","state":"queued","document_id":"doc-1","target_generation":5} +``` + +```json +{"job_id":"job-03","state":"succeeded","result":{"document_id":"doc-1","revision":3,"kind":"created"}} +``` + +精确版本目录和批量读取: + +```json +{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +``` + +```json +{"chunk_ids":["chunk-1","chunk-2"]} +``` + +```json +{"knowledge_base_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +``` + +```json +{"hits":[{"knowledge_base_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} +``` + +检索 limit 计 chunk 数;可选 snippet 有界,正文从 chunk 接口获取。通用 Artifact search 继续返回 Artifact,不混入 chunk 响应。 +索引命中必须对应当前 manifest 的 result_id 和索引 profile,并满足归属、权限及删除规则;过滤后继续补取候选,避免无效结果占满 top-k。 +适配覆盖首次写入、版本替换、重建、coverage/摘要核对、零块、删除过滤和命中定位。保留历史正文不要求保留所有历史索引。 +重建可暂停发布,但不能发布缺失所需索引的新内容;旧可用索引在替代结果发布前保留。 + +同 Scope 可选择多个知识库;跨 Scope helper 逐个授权显式目标,调用同一分 Scope 接口,融合排名并保留目标身份/错误, +不直接比较不兼容向量空间的原始分数。不支持的 filter/rerank 明确拒绝。Python/MCP 复用同一业务服务。 +权限复用 Scope 读/贡献和 Artifact 写/治理能力,跨对象请求逐个检查。接受失败沿用 428/412 前置条件、409 冲突、410 已删除、 +422 校验、413 大小限制和 503 不可用;202 后的失败记录在任务状态中,不再靠日志推测。 + +## 9. 实施与验收 + +仅新增插件存储迁移,已有核心表无需新增字段/迁移。插件框架需提供能力注册、消费准入、受限发布和可见性检查; +“不改表结构”不代表“不需要通用框架适配”。公开路由按主契约/插件 OpenAPI 的归属生成绑定。 + +SQLite、SeekDB、OceanBase 都验证: + +- 同 Scope 多知识库、跨库授权、独占归属、原文排他消费,包括恢复扫描和手动入口。 +- 固定 oceanbase/oceanbase commit 的编译运行、调试和 Wait Event 文档;真实文字图片与 OCR 来源映射。 +- 同请求重放、不同参数冲突、同目标活跃冲突、内容去重、配置重解析和人工编辑保护。 +- 任务接受后退出、Source 已登记但未确认、租约重领、迟到 token、目标替换、有限重试和取消。 +- 结果准备后 core 回滚、core 成功但任务确认失败;旧版本可用、结果不提前可见、不重复发布。 +- 创建/修改/删除证据与实际 revision 一致;删除 chunk 版本递增、零块可读、历史保留。 +- Source/document/knowledge-base 删除与发布竞争,可恢复级联,所有普通/精确/历史/证据读取阻断。 +- Chunk 目录/单块/批量边界、索引全生命周期、重建及有效候选补取。 +- OpenDAL 本地快照对 Server/Worker 可访问,原文件随后变化不改变已接受输入。 + +真实后端和真实 OCR 验收不能由 mock 替代。先用小样本对比两种规则的答案片段召回、SOP 完整性及出处,不宣称已有质量或规模结论。 +#2441 承担接入/资源归属,#2442 承担队列/处理/发布,#2443 承担检索/接口,#2444 承担运行与验收;不新增 Issue。 + +# 缺点 + +三张业务表及索引需要插件自己迁移、备份和恢复。独立存储需要发布对账和短提交闸门;完整 chunk 快照、成功操作证据、软删除及终态任务 +都会增加存储。资源表两类记录需要明确约束。首期不提供跨库分布式事务或大规模性能保证,索引重建可能影响同 Scope 的多个知识库。 + +# 设计理由与替代方案 + +- 一个业务插件集中管理归属、任务和配置,内部解析模块仍可独立扩展。 +- 三张插件表在不改核心模型的前提下提供逐 Source 删除和逐文件任务;资源登记合并固定两类记录,避免额外文档状态/回执表。 +- Source 保存不可变内容与成功证据,jobs 保存可变执行状态;不把待执行命令伪装成成功操作 Source。 +- Artifact 管理整篇版本,chunk 明细支持精确读取;直接编辑旧行无法保留历史。 +- 独立队列适合慢解析及外部等待,不依赖原有消费 cursor;只复用 Supervisor 可分离的运行工具。 +- 不可变结果先准备、core 再发布、任务最后确认,尊重插件存储隔离;跨库原子事务不是默认能力。 +- 删除 revision 提供稳定操作证据,head retirement 和读取 guard 控制可见性;仅清除搜索索引不足以删除内容。 + +# 既有设计 + +基于 [插件接口 #2549](https://github.com/oceanbase/powercontext/pull/2549)、[插件 API #2579](https://github.com/oceanbase/powercontext/pull/2579)、 +[Source 身份](1400_source_definition_and_observation_model.md)、[处理监督](1515_artifact_processing_supervisor.md) +和 [Source/Artifact API](1437_source_artifact_rest_api.md)。复用原文身份、Artifact revision、成功操作证据和治理机制, +独立实现知识库任务与 chunk 投影。现有 Atomic Memory retirement 不自动提供 Source 级联删除或插件生命周期检查。 + +# 待解决问题 + +实现前固定复合插件注册/受限 writer 签名、发布与删除闸门的后端锁顺序、通用读取 guard 接入和 Source 排他消费准入。 +实现时固定 OCR 模型、切块参数、任务租约/并发/重试限额、API 数量/字节上限及 schema 具体类型。这些不改变本文的数据归属和提交语义。 +恢复/擦除、任务归档幂等保留期、改名身份、逐知识库向量空间与完整编辑文档导出另定契约。 + +# 后续可能性 + +增加 Word/PDF/场景图解析器时复用任务、切块、发布和检索流程;外部解析通过保存远端引用并轮询继续,无需首期建设完整解析框架。 +可进一步增加 OpenDAL provider、rerank、邻接/父章节上下文和受限多步检索。扩展效果与成本需要实测,不作为首期前置条件。 diff --git a/docs/zh/rfcs/2570-rag-knowledge-base.md b/docs/zh/rfcs/2570-rag-knowledge-base.md deleted file mode 100644 index 0932675081..0000000000 --- a/docs/zh/rfcs/2570-rag-knowledge-base.md +++ /dev/null @@ -1,450 +0,0 @@ ---- -title: "RFC 2570:基于 rag Artifact 的文档知识库" -description: "复用 Source journal、后台 Worker 与 Source 生命周期元数据,实现 OpenDAL 接入、文档 chunk 版本和知识库检索。" ---- - -- Proposal Name: `rag_knowledge_base` -- Start Date: 2026-11-10 -- RFC PR: [#2570](https://github.com/oceanbase/powercontext/pull/2570) -- Tracking Issue: [#2440](https://github.com/oceanbase/powercontext/issues/2440) -- Related Issues: [#2441](https://github.com/oceanbase/powercontext/issues/2441), [#2442](https://github.com/oceanbase/powercontext/issues/2442), [#2443](https://github.com/oceanbase/powercontext/issues/2443), [#2444](https://github.com/oceanbase/powercontext/issues/2444) - -# 概述 - -通过 Source 插件和 document、rag 两个 Artifact family 提供文档知识库。一个 Scope 可有多个用户创建的 rag, -每个文档 Source 和整篇 document Artifact 唯一归属一个 rag。OpenDAL 采集不可变原文,Markdown 与图片 OCR 共用简单切块。 -异步操作请求保存为不可变 Source,通过现有 journal、cursor 和 Worker 消费;document revision、chunks、lineage、索引与消费游标原子提交。 - -新增一张文档 chunk 表,并给 pc_sources 增加通用软删除字段。复用 Artifact 存储和后台处理表,不另建导入/任务/状态平台。 -展示内容是否可用,不提供持久逐文件执行状态。本文是建议契约,不表示功能已发布。 - -# 动机 - -业务描述和 SOP 需要整篇文档的片段检索、精确出处、显式更新和可预测的删除。记忆提取无法保留每个片段。 -首期应依托现有 Source/Artifact 基础设施覆盖该流程,同时明确失败语义。 - -原文快照、已接受的操作请求和成功 Artifact revision 各有职责,不能把可变任务状态写入 Source payload。 -检索从已提交 chunks 派生,与 Memory 索引及配置隔离。复用仍需实际适配 family、读取、投影和 Worker。 - -# 使用层说明 - -1. 在现有 Scope 中通过通用 Artifact 创建空 rag。 -2. 使用配置好的 OpenDAL Source 插件,选择 rag 与本地目录/文件。 -3. 查看“已生成/有更新待生成/尚未生成”;没有结果不代表已经失败。 -4. 检索明确选择且已授权的 rag,更新失败时继续使用原提交内容。 -5. 导入变更文件或显式重新解析,从固定原文整篇生成新 revision。 -6. 异步编辑/移除 chunk;先接受请求,成功时提交新 revision,保留历史。 - -用户无需提供文件 hash、namespace 或 document ID。Scope 保持授权边界,同文件导入两个 rag 产生不同逻辑 Source/document, -可选复用物理快照字节。首期支持 Markdown 和独立导入的文字图片,OCR 使用 RapidOCR + ONNX Runtime。 -Markdown 内图片只保留引用,不抓取或 OCR。SQLite、SeekDB、OceanBase 均支持完整流程,一个部署选择一种后端。 - -首期不包括 PDF/Office、独立 TXT 导入、语义/LLM 切块、复杂布局恢复、定时目录同步、逐 rag embedding 空间、 -无停机索引切换、任务管理 UI、逐文件持久失败详情、恢复/永久擦除或大规模性能验收。 - -# 参考层说明 - -## 1. 归属与插件配置 - -```text -Scope - rag R1 - 原文 Source S1 -> 操作 Source Q1(import)-> document D@1 -> chunks - 操作 Source Q2(edit D@1)-> document D@2 + 成功编辑证据 E2 - 原文 Source S2 -> 操作 Source Q3(reparse)-> document D@3 - rag R2 - 独立的原文 Source、请求和 document - -Source 插件:OpenDAL 采集、快照访问、原文与受信操作 Source 类型 -Document 插件:Markdown/OCR、chunks、revision、操作消费、溯源与 chunk 索引生命周期 -rag 插件:集合配置与 document chunk 检索编排 -共享设施:Source/Artifact API、Supervisor/Worker、cursor、事务、数据库/模型适配器 -``` - -三个逻辑插件可放在同一集成包,应用服务负责协调,不新增第四个插件。Rag 可先于 Source 存在,配置使用 Artifact revision, -删除使用 head 治理。知识库 Scope 只启用文档业务:文档 Source、document 和预创建的 rag;请求/编辑证据是这条管线的内部记录, -不是其他 family 的输入。通过 Scope 接受规则和消费 binding 执行限制,无需新增 Scope 表。 -不设 rag 运行状态表。归属显式保存在不可变 Source payload 和 document manifest,不从 tags 或证据 lineage 推断。 -每个原文、请求和 document 只属于一个 rag。 - -插件独立持有 embedding/索引配置。显式配置优先;安装时可从主路径初始化兼容的缺省项,并固定解析后的 profile 和凭据引用。 -不把密钥写入 Artifact,也不自动跟随之后的主路径配置变化。Parser/OCR/chunker 可按 rag 配置;首期 embedding/索引 profile -为插件级,在同一 Scope 的 document family 共用。按 family、索引定义和向量空间隔离,模型/维度变化走现有 family 重建机制。 - -文档原文只允许 document 管线直接消费,操作请求只允许其处理器执行。在选择、执行和提交环节校验资格;仅注册新 Source 类型 -并不能阻止已有通用消费者使用它。请求不作为普通生成输入或检索文本。 - -## 2. OpenDAL 导入、身份与去重 - -OpenDAL/opendalfs 负责本地列举/读取和受管目录中的不可变快照。插件实例必须能访问选定路径。固定根目录、相对路径和 -符号链接规范化策略,拒绝越界。先保存快照,再接受 Source,对保存字节计算 hash 并解析该快照,不能解析随后变化的文件。 -mtime/size 仅是提示,不证明内容相同。复用已有 Source 时保留首次 canonical 采集信息。 - -首期仅支持本地可访问目录,使用 OpenDAL fs 后端。导入进程、Server 和 Worker 必须能访问同一受管快照目录, -可直接访问或使用本机容器卷映射;接受处理请求前校验存储配置与访问能力。Source 用 original_path 记录出处, -用 snapshot_ref(store_id、object_key、digest)供实际读取,存储别名解析到各进程配置的本地根目录。 -原文件随后修改或移除,Worker 仍读取已采集快照。远端客户端上传、跨机器文件传输、对象存储原文和远端共享存储均不在本期范围。 - -```text -file_key = (scope_id, rag_id, collection_id, normalized_relative_path) -document_id = stable_hash(identity_version, file_key) -content_digest = SHA256(captured raw bytes) -source_key = stable_hash(source_schema_version, file_key, content_digest) -processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) -index_key = hash(complete embedding inputs, plugin profile and projection versions) -``` - -Collection 由已注册存储实例/绑定和规范化根目录派生,不使用 scan token。Hash 命中还需核对完整身份,不截断路径或仅按摘要合并。 -原文 payload 包含 owner rag、文件身份、原始路径、document ID、media type、摘要和快照引用。Artifact 尚未存在时即可得到相同的 -确定性 document ID,无需预留表行。 - -| 情况 | 行为 | -| --- | --- | -| 同文件/内容/处理 profile,已有可用成功结果 | 复用 Source/document,跳过解析,单独检查索引就绪情况 | -| 存在尚未消费的等价请求 | 扫描未消费 journal 时可合并;并发重复 import 在执行时再次检查成功结果 | -| 同输入但无成功结果 | 显式重试可创建新请求;采集 checkpoint 不等于处理成功 | -| 同路径字节变化 | 新原文 Source,相同 document ID,成功后整篇新 revision | -| Parser/OCR/chunker 变化 | 复用原文 Source,显式请求重处理 | -| 仅 embedding/索引变化 | 从已提交 chunks 重建,不重复 OCR | -| 同内容不同路径/rag | 不同逻辑 Source/document,可选复用物理快照 | -| 人工编辑/移除后原文未变 | 保留人工版本,不把人工正文 hash 当原文 hash 比较 | -| 重新解析人工修改过的文档 | 必须明确 manual_edits_policy=discard,否则保留当前内容并拒绝冲突 | - -文件回到旧字节可能复用较早的 Source,因此期望输入依据最新接受的 import/reprocess 请求,而不是最大原文 Source journal position。 -找到 Source 不证明当前 document 已匹配。首期改名视为新身份,目录文件消失不自动删除。已删除 Source 身份与 retired document -不能被静默恢复。 - -Parser/chunker 选择不参与 document 身份。同一 Source 改用新的切分方法时,显式重解析沿用 document_id 和 rag_id, -内容/索引准备成功后提交下一个 revision,替换当前有效内容和索引,不覆盖历史行。失败保留旧 head; -已有人工修改仍需明确 discard 授权。重新切块可以产生新的 chunk ID。 - -复用 Source collect 的发现/add/status/control。客户端生成的 scan_token 放在插件 input 中标识一次显式扫描;重试相同输入 -复用采集目标。再次扫描使用新 token,但文件身份不变。每 token 扫描一次,不暗示定时同步或重复 add 会启动 stopped target。 -采集状态仅描述接入;扫描还需检查成功 document 结果,不能只看 checkpoint。 - -## 3. Markdown 规范化与切块 - -```text -Markdown 字节 -> markdown-it-py 结构/字节映射 -----+ - +-> 规则切块 -图片 -> RapidOCR 文字/区域 -> 规范化 Markdown -----+ -``` - -OCR 保留实际文字、顺序、置信度和原图区域,包括预处理坐标变换。规范化只转义 Markdown 语法、组织行/段落,不虚构标题、 -不做 LLM 校正或复杂表格恢复。规范化文本跨度映射回 OCR 行和原图区域,并声明 locator 精度。派生 Markdown 不替换图片 Source。 - -按标题、段落、列表和代码块组织,短块合并至 max_chunk_chars,过长块按句子/长度拆分,可用 overlap_chars 保留上下文。 -保留标题路径、语言和续块标记。Overlap 必须小于最大长度,1200/100 仅为待验证示例;调用 embedding 前校验包含标题/前缀的 -完整输入 token 预算,不能静默截断。 - -明确校验格式、UTF-8、图片解码/像素上限、OCR 模型、超时和无文字结果,固定并验证真实 RapidOCR、ONNX 和模型版本。 -OCR 无文字不算成功空文档;显式移除最后一个 chunk 则允许。无需独立章节树、解析节点表或完整 Markdown 缓存。 -Chunk metadata 保存有界出处映射,canonical chunks 不存向量,Artifact manifest 不存全文。 - -## 4. 持久化:一张明细表与 Source 生命周期字段 - -不新增 pc_document_imports、pc_document_source_states。Source payload 保存不可变身份/请求,Artifact 保存成功 revision, -现有处理表协调消费。不能用 rag content、Scope settings、checkpoint 或 cursor 中的无界字典替代这些表。 - -| 复用设施 | 职责及结构变化 | -| --- | --- | -| pc_sources | 原文、操作请求、成功编辑证据;增加下述通用生命周期字段 | -| Source journal/heads、connector checkpoints | 接受顺序和采集进度,结构不变 | -| pc_source_cursors | document binding 的连续扫描位置和 CAS generation,结构不变 | -| Processing intents、leases、binding state | Scope/binding 唤醒、调用代次和执行栅栏;结构不变,不是逐文件任务表 | -| pc_artifacts、pc_artifact_heads | rag 配置、document manifest、当前 revision 和 retirement/治理,结构不变 | -| Source/Artifact lineage、locators、tags | 原始输入、请求、base revision 和成功编辑证据,沿用结构 | -| Artifact search states/coverage/changes/text/vectors | 当前版本片段索引和构建协调,复用设施并增加 chunk 投影适配 | - -给 pc_sources 增加: - -| 字段 | 类型/默认值 | 语义 | -| --- | --- | --- | -| lifecycle_state | 短字符串、NOT NULL、默认 active | active/deleted,首期单向转换 | -| deleted_at | 可空 UTC 时间 | 首次删除时间,重复删除不刷新 | - -已有 Source 回填 active,payload、身份和 journal position 保持不可变,生命周期元数据不参与内容 hash。 -通过行锁/条件更新和统一锁定顺序与 document 提交互斥,首期不额外增加 Source 删除代次列。 -适配 add/get/list、证据/生成访问和 family 读取;重复 add 命中已删身份时不能返回可用内容或恢复。 -内部迁移/级联扫描可包含已删行,公共读取不能绕过。本期删除能力只覆盖知识库管线的原文和内部记录, -不扩展到无关 Source 类型或其他 family 级联。三个后端验证加法迁移,不能把 Artifact retirement 当作已有 Source 软删除能力。 - -唯一新增领域表为 pc_document_chunks: - -| 约束/字段 | 设计 | -| --- | --- | -| 主键 | (scope_id, document_id, revision, chunk_id) | -| 唯一顺序 | (scope_id, document_id, revision, ordinal) | -| 内容 | text、content_digest | -| 结构 | 标题路径、续块/重叠元数据 | -| 溯源 | 规范化跨度、原文字节/图片定位、origin/verbatim、base/edit 引用 | - -使用后端安全键长与有界元数据。每个 revision 是完整不可变 chunk 快照:100 块移除一块生成新 manifest 和 99 行,保留旧的 100 行。 -现有 Artifact 封装标识 document/revision,有界 manifest 保存标题、owner rag、文件身份、root SourceRef、处理指纹、 -chunk 数量/摘要、人工修改标记和 applied_request_ref。客户端由精确 document 引用确定 chunk 目录路径; -manifest 不嵌入 chunk 正文或无界 chunk ID 列表。历史读取使用精确 revision,而非当前 head。 -Chunk 行提供 text_length(Unicode 码点数量),供目录只返回长度等元数据,不返回正文。 - -首期成员和可用性查询可以按 Scope/类型分页扫描解码 payload,再按确定性 document ID 精确读 Artifact。不能假设 canonical payload -已具备可查询的 JSON owner/path 索引。过滤分页按扫描位置继续,不能丢失后续匹配项;写入/读取验证归属和完整身份。 -扫描有成本,本方案不承诺大规模性能。额外投影需有测量依据,不能隐式重新引入任务表。 - -## 5. 操作 Source、Worker 与事务边界 - -受信应用服务创建专用操作 Source 类型,示意名 document_operation,原文示意名 document_file;它们是插件注册,不是新存储表。 -请求保存 owner rag、document ID、operation、root SourceRef、固定处理配置/指纹、request ID、base revision,以及有界编辑/discard 参数。 -首次导入可无 base,编辑必须固定已有 base。Payload 不包含可变 state、attempt、error 或未来输出 revision,普通用户 metadata 不能伪造命令。 - -Import/reprocess 从固定原文整篇生成;edit 支持 replace_text、remove。现有 ContentSourceInternal 表示成功 artifact_create/artifact_replace, -且绑定精确 revision,不能表示未执行命令。保留其成功语义,待执行请求使用专用类型。 - -原文接受/复用、请求插入和 document binding 的 processing_intents.request() 同事务完成。只有新接受的请求发布新工作。 -需显式适配 Source/binding 通知,当前 SourceRepository 不会自动发现本方案的 processor。 - -请求身份在 Scope/rag/document/operation 和客户端 request_id 范围确定性生成。Canonical payload 相同的重放返回已接受请求, -相同身份但不同内容冲突。重放已消费请求不再次执行;显式重试使用新 request ID,可复用同一原文 Source。 -只增加调用计数不能重新执行已被 cursor 越过的输入。 - -```text -请求 Source + processing intent 原子接受 - | -现有 Worker 顺序扫描 document binding 的 journal 窗口 - | -事务外准备 chunks/embedding - | -document + chunks + lineage + 索引 + cursor 原子提交 -``` - -同 Scope/document binding 内顺序处理,采用有界窗口和既有栅栏/cursor CAS。不相关 Source 只推进连续扫描边界。 -不提供逐文件队列或“最新请求自动取消旧请求”的保证。请求固定 base;前序操作改变 head 时,后续请求可能冲突,不能静默换 base。 -用户刷新后提交新请求。执行期间接受的新 Source 不修改运行中的请求。Scope invocation 依照既有 ScopeInvocation 契约确认, -处理部分工作不能把整个窗口标成 clean。 - -Cursor 表示已消费,包含跳过,不表示成功。成功 revision 通过 applied_request_ref 和 lineage 关联请求;没有持久逐请求失败回执。 - -| 结果 | Cursor 与恢复 | -| --- | --- | -| 单输入解析/OCR/配置错误或 base 冲突 | 记录脱敏标识/错误,在执行栅栏保护下越过该请求,保留旧内容,继续其他输入 | -| 请求局部短暂错误 | 可在进程内有限重试,耗尽后同样记录并跳过,不持久保存 attempt | -| 数据库故障、索引重建或系统性模型不可用 | 不推进该请求,复用 Supervisor 退避/恢复,报告 binding 级不可用 | -| 提交前进程退出 | Cursor 未推进,恢复后重执行固定请求 | -| 成功提交后进程退出 | 内容与 cursor 已提交,不重复创建 revision | -| 输出失败日志后、跳过事务前退出 | 可能重新执行,允许重复诊断 | - -日志遵循现有可观测性契约,不包含正文、凭据或敏感路径,也不是恢复依赖。已消费失败请求需显式新请求重试。 -运行时任务状态或请求超时不能证明永久失败。 - -| 边界 | 工作 | -| --- | --- | -| 事务外 | 快照采集、解析/OCR、完整 chunk 快照、embedding 和索引投影准备 | -| 接受事务 | 权限、归属/生命周期/base 校验,Source/请求接受,processing intent | -| 成功内容事务 | 重验 Worker/cursor/base/owner/root/索引栅栏;提交 manifest、chunks、lineage、必要成功编辑证据、head、索引及 cursor | -| 失败跳过事务 | 重验执行/cursor 栅栏并推进连续边界,不写 document 或成功编辑证据 | -| 删除事务 | 标记 Source 生命周期或 retire Artifact head,由父/root 校验阻止并发发布 | - -模型调用和 DDL 在内容事务外。Chunk 投影从 chunks 准备,不从 manifest 中假设存在全文;提交验证快照和投影指纹。 -新内容与索引一起可见,更新失败保留旧 head/索引。Family 重建时延后 document 提交,不走通用“仅提交内容”路径。 -重建读取已提交 chunks,不重复 OCR;明确不可用,不回退 Memory/纯全文,也不保证零停机。 -三个后端需验证实际事务,包括 SQLite 写锁;ANN 过滤限制需通过限定集合精确检索或明确能力错误处理。 - -Document 插件负责统一的精确版本 chunk 投影边界,覆盖首次写入、版本替换、重建、coverage 校验、删除过滤和检索。 -重建读取精确已提交 chunk 行,不能把有界 manifest 当全文。Coverage 核对 manifest 数量/摘要、该 revision 的 chunks 与投影; -零 chunk revision 对应合法的零片段 coverage。评分/融合保留精确 document revision 和 chunk ID,使后续读取能定位实际命中。 -通用投影/重建代码需要接入该边界,只适配首次写入不足以完成实现。Rag 服务复用这些投影,不改变通用 Artifact 搜索结果契约。 - -## 6. 编辑、chunk 移除与删除 - -编辑 If-Match 在接受和提交时分别校验,成功生成完整新快照。未变 chunk 保留逻辑 ID,重切块分配新 ID;引用始终带 revision。 -移除最后一块后保留可读零块 manifest,当前索引没有片段;任何移除都不物理删除历史 chunk 行。 - -成功时创建系统 Content Source,role=lineage_only、operation=artifact_replace,绑定真实新 revision,记录请求/base/root 修改依据。 -显式保留原始 Source 依赖。编辑文字标记 origin=manual_edit、verbatim=false,原图坐标只表示修改依据,不证明新文字逐字存在。 -Remove 同样算人工修改,重新解析需明确丢弃授权。完整 embedding 输入未变可复用计算,但索引映射仍需指向新当前 revision。 - -| 删除操作 | 行为 | -| --- | --- | -| 原文 Source | Source lifecycle 标记 deleted,retire 当前仍以它为 root 的 document,并撤销相关历史读取;其他 root 完整重解析的版本保留 | -| Document | Retire head,阻断所有 revision/chunks 和后续命令,原文 Source 保持 active | -| rag | Retire head,立即阻断所属内容,再可恢复地标记全部所属 Source(含请求/编辑证据)和 document head | -| Chunk | 提交不包含该块的新 revision,保留历史 | - -复用 Artifact lifecycle_state=retired 和治理 CAS。原文 payload/快照及历史业务内容保留,不动用户文件,首期无恢复/永久擦除。 -尚无 head 的导入文件通过原文 Source 删除;document DELETE 返回不存在,不虚构占位 Artifact。 -删除待处理替代 Source 不 retire 仍依赖另一 root 的旧提交版本。 - -检索和通用精确/历史/chunk 读取检查 owner rag、document head 和精确 revision 的 root。历史 base 链接不让完整重解析版本传递依赖旧 root。 -原文读取校验自身状态/owner,单删 document 不隐藏原文;请求/编辑证据读取还需校验目标 document,避免保留的人工正文绕过删除。 -删除请求会阻止尚未消费的执行,不撤销已提交编辑;内容有效性由 root/document/rag 决定,而非事后取消请求。 - -通用 retirement 可能仍允许精确读取,需增加 family guard。大规模 rag 级联从 retired 父对象和不可变归属重新发现剩余工作, -内部包含已删行,无需 cascade job 表。即使传播未完成,也必须在排名前排除无效对象。 -派生索引沿用替换/移除/重建;保留业务历史不等于保留每个历史索引条目。 - -## 7. 可用性、Artifact 接口与 chunk 读取 - -| 展示 | 推导依据 | -| --- | --- | -| 已生成 | 有可用提交 revision,匹配选定原文/配置,保留有效人工修改 | -| 有更新待生成 | 有可用旧 revision,但期望原文/配置不同;旧内容仍可检索 | -| 尚未生成 | Source 已接受但无可用成功 revision,可能未开始、运行中或失败 | -| 已删除 | Source 或所属 Artifact 生命周期无效,不返回保留正文,普通列表默认排除 | - -期望输入取最新接受的 import/reprocess 请求,无请求时取已接受原文。人工编辑不是原文件不匹配。 -Rag 配置变化影响后续请求,可提示需要重处理,但不自动入队。不展示逐文件阶段、百分比、attempt 或持久错误, -不从采集完成/cursor 推进推断成功;binding 诊断和索引可用性单独处理。 - -复用权限、错误、引用、分页、ETag 与 SDK/MCP 操作。必要契约改动写入 openapi/powercontext.yaml 并生成绑定。 -当前通用 create-Source 只接受 built-in content,文档文件使用 Source 插件协议。 -约定 `R=/v1/scopes/{s}/artifacts/rag/{r}`,`D=/v1/scopes/{s}/artifacts/document/{d}`。 - -| 操作 | 现有路由或必要扩展 | -| --- | --- | -| 创建/配置 rag | 现有 POST `/v1/scopes/{s}/artifacts`、GET/PUT R、revisions/tags,完整替换与既有前置条件 | -| 导入/控制 | 现有 POST `/v1/source-management/add`、collect capability/instance 和 status/target/instance controls | -| 文件与可用结果列表 | 现有 Source list/get、Artifact list/get/history,验证 owner-rag filter,helper 按 document ID 合并;不设 R/processing 任务列表 | -| 显式重解析 | POST D/processing,source_ref、action=reprocess、request_id、可选配置/discard;202 表示请求接受 | -| 编辑/移除 chunk | POST D/edits,当前 If-Match、有界类型化操作和 request ID;202 表示请求接受 | -| 获取 document | 现有 Artifact GET/历史接口,返回标题、精确版本、归属、chunk 数量和原文引用,不返回 chunk 正文 | -| 获取 chunk 目录 | GET `D/revisions/{rev}/chunks`,分页返回 ID/顺序/标题路径/长度等元数据 | -| 获取单个 chunk | GET `D/revisions/{rev}/chunks/{chunk_id}`,返回正文、出处和人工修改标记 | -| 批量获取 chunk | POST `D/revisions/{rev}/chunks/batch-get`,按明确且有界的一组 chunk ID 返回正文 | -| 知识库检索 | 新增 POST `/v1/scopes/{s}/rag/retrieve`,明确 rag_ids、query/mode/limit,返回 chunk 命中引用 | -| 软删除 | 在既有精确 Source/Artifact 路由增加 DELETE;Artifact 治理 expected_generation,Source 单向生命周期 | - -已有 head 的重解析需 If-Match,无 head 时使用确定性 document ID 和 If-None-Match: *。验证 Source 归属/文件身份确实解析到该 ID, -执行时重验 base。不把 Scope invocation generation 作为 document target generation 返回。 -Document 操作复用 scope.contribute,rag/Source 删除复用 scope.admin,读取沿用既有授权。 - -创建 rag: - -```json -{"family":"rag","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} -``` - -目录采集,capability/instance 为部署发现值示意: - -```json -{"scope_id":"project-p","capability":"knowledge-documents.collect","capability_version":"1","instance_id":"local-documents","input":{"rag":{"family":"rag","artifact_id":"ops","revision":1},"root":"/work/docs","scan_token":"scan-01"}} -``` - -POST D/edits 移除 chunk,携带当前 document ETag: - -```json -{"request_id":"edit-03","operation":{"kind":"remove","chunk_id":"chunk-3"},"reason":"Remove an obsolete instruction"} -``` - -202 回执说明持久接受,不表示 pending 状态或未来 revision: - -```json -{"accepted":true,"document_id":"doc-1","request_source":{"source_type":"document_operation","source_id":"request-03"},"current_revision_at_accept":2} -``` - -current_revision_at_accept 是观察值,不是输出。通过 revision 的 applied_request_ref 确认成功,没有匹配 revision 不证明失败。 -重新执行需刷新前置条件并使用新 request ID,相同请求重放返回原接受事实,不是新的执行结果。 - -显式重新解析,已有 document 使用 If-Match,并授权丢弃人工修改: - -```json -{"action":"reprocess","request_id":"reparse-04","source_ref":{"source_type":"document_file","source_id":"source-1"},"manual_edits_policy":"discard"} -``` - -Document GET/精确历史沿用 Artifact 封装和有界 manifest。Chunk 目录使用 items/next_cursor,按 ordinal 排序, -不返回正文或摘要片段。Cursor 绑定 Scope/document/revision,head 并发变化不会混入其他版本;单个和批量读取也使用同一精确版本, -不回退当前 head。三个 chunk 入口均校验 owner/document/root 生命周期,包括历史读取。零 chunk revision 返回空目录。 -单个 chunk 返回 text、source_ref/locator、origin/verbatim 和编辑依据。 - -Batch-get 接受非空、无重复的 chunk_ids,按请求顺序返回,不允许混合 revision。限制配置的 ID 数量与响应字节数, -超限拒绝而非截断正文。先授权父对象,再验证该 revision 内的所有 ID;任一 ID 不存在则整个批次返回 404,不静默忽略。 -已删对象沿用授权后 410。该接口仅批量读取,不是通用批量修改接口。 - -一个精确 revision 的目录响应示例: - -```json -{"document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} -``` - -POST `D/revisions/2/chunks/batch-get` 请求: - -```json -{"chunk_ids":["chunk-1","chunk-2"]} -``` - -知识库检索使用 POST `/v1/scopes/{s}/rag/retrieve`,不套用通用 Artifact 搜索响应: - -```json -{"rag_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} -``` - -结果为有界 chunk 命中,携带 rag ID、精确 document 引用、chunk ID、得分和原文定位;可选摘要片段必须有界,不能替代正文接口。 -这里 limit 计算 chunk 命中数。例如: - -```json -{"hits":[{"rag_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":2},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} -``` - -通用 Artifact GET/历史/搜索契约保持原义:Artifact 搜索返回 Artifact,不能随意返回 chunks 或另一 family 的 document。 -Document 专用内部处理器复用索引/模型设施,独立 rag 检索入口避免给所有通用搜索项增加知识库 matches。 -要求非空且经过验证的 rag 选择,排名前过滤归属和生命周期。不支持的 filter/rerank 明确报错。 -跨 Scope helper 逐个授权明确的 (scope, rag),调用同一分 Scope rag 检索接口,按排名融合并保留目标错误/身份,不比较不兼容原始分数。 -HTTP、Python、MCP 提供等价的概览、chunk 读取与检索操作,复用公共授权和错误封装。 - -接受阶段沿用 428/412 前置条件、409 payload/discard 冲突、授权后 410 删除、422 校验(传输层可用 413)和 503 服务不可用, -保持 error.code/message/details 错误封装。202 之后的请求局部失败/冲突按日志与消费规则处理,不提供持久错误状态端点。 - -## 8. 实施与验收 - -复用仍需 Source 生命周期迁移/读取 guard、受信请求接受、消费者限制、document binding 通知、journal 选择/cursor 事务、 -chunk 投影和 top-k 前归属过滤。不代表框架无需适配,也不代表当前路由已经全部支持。 - -SQLite、SeekDB、OceanBase 使用相同公开流程验证: - -- 多 rag/Scope、文件归属独占、授权选择与不串库。 -- 固定 oceanbase/oceanbase commit 的 Markdown 和真实 OCR fixture,保留准确出处。 -- Source 迁移回填、payload 不变、已删重放拒绝、精确/历史/证据读取校验。 -- 成功去重、失败后新请求重试、配置重解析、仅 embedding 变化重建。 -- 请求/intent 原子接受,重启恢复,内容/cursor 原子提交,相同请求不重执行。 -- 单输入失败推进与系统性故障保留,cursor 推进绝不表示文件成功。 -- 异步 base 冲突/迟到 Worker、失败不生成成功编辑证据、人工修改保护。 -- Chunk 移除包括最后一块,历史完整,当前索引正确。 -- Source/document/rag 删除竞争,可恢复级联,替代 root 独立性。 -- 插件配置独立、索引隔离、重建不可用、分页、契约生成和 SDK/MCP 一致性。 -- Document/目录只读元数据,精确版本的单个/批量 chunk 正文、字节/数量上限及不存在 ID 的行为。 -- 同一 Source 更换切块方法保留 document/rag 身份,更新当前 revision 并保留历史。 -- Chunk 投影/重建/coverage 一致,包括零块和检索命中精确定位。 -- OpenDAL 本地快照对导入进程/Worker 可访问,包括本机容器映射;不接受远端路径。 - -Mock 不证明真实后端/OCR 支持。#2441 负责接入/归属/Source 生命周期,#2442 负责处理、请求/chunks/原子写入, -#2443 负责检索/接口,#2444 负责诊断/验收。一个实现分支/PR 可分阶段交付;RFC 不关闭实施 Issue,也不证明大规模容量。 - -# 缺点 - -操作 Source 增加 journal 行,完整 chunk 快照和软删除保留消耗存储。顺序消费可能等待前序文件;可用性展示没有逐请求持久失败详情, -首期 owner/请求过滤可能扫描 payload。Family 重建可中断多个 rag。这些是首期明确取舍,Source 生命周期、消费者/投影适配仍有实际工作量。 - -# 设计理由与替代方案 - -- 多 rag Artifact 保留项目级 Scope,不把集合组织与授权绑定。 -- Source journal 持久保存已接受操作,无需新增可变任务表;仅内存命令在重启时会丢失。 -- 请求 Source 保存意图,精确成功编辑 Source 保存结果;提前使用后者会错误表达溯源。 -- Source 生命周期字段表达通用删除,payload 仍不可变;文档专用 sidecar 重复承担该职责。 -- 整篇 manifest 配合 chunk 明细避免巨大正文 JSON 和逐 chunk Artifact 身份。 -- 不可变 revision 替换保留旧数量/摘要/引用,直接删 chunk 做不到。 -- 独立任务/发布系统可提供更丰富的状态/切换能力,但不在接受范围内。 - -# 既有设计 - -基于 [Source 插件](2012-source-plugin-system.md)、[Artifact 插件](2175-artifact-plugin-system.md)、 -[Source 身份](1400_source_definition_and_observation_model.md)、[处理监督](1515_artifact_processing_supervisor.md) -和 [Source/Artifact API](1437_source_artifact_rest_api.md)。现有 OpenDAL hash、Source cursor CAS、Artifact head 治理和片段索引 -提供基础,并非完整知识库实现。Atomic Memory retirement 也不等于已存在 Source 到 document 的级联契约。 - -# 待解决问题 - -实现时固定 Source/capability 签名、图片/模型版本、资源与切块默认值、有限重试错误分类、后端迁移/索引事务行为。 -新增查询投影必须有测量依据。逐请求持久结果、恢复/擦除/GC、改名身份、逐 rag 向量空间和完整编辑 Markdown 导出另定契约, -不能直接拼接重叠 chunks 重构完整编辑文档。 - -# 后续可能性 - -通过组件边界扩展 OpenDAL provider、解析器、切块器、rerank 与受限 agentic 检索。测量后再考虑共享不可变 chunk 正文、 -更丰富任务状态或面向集合规模的查询投影,这些都不是首期归属、请求恢复、版本内容和精确证据的前置条件。 From 0256c4f35985f64fe7a1558462fcc88a0636d0f3 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Wed, 11 Nov 2026 21:39:42 +0800 Subject: [PATCH 08/13] docs(rfc): close publication and lifecycle recovery gaps --- docs/en/rfcs/2570-knowledge-base.md | 146 +++++++++++++++++++++++----- docs/zh/rfcs/2570-knowledge-base.md | 109 +++++++++++++++++---- 2 files changed, 211 insertions(+), 44 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index 2ad6cdc91c..f37d8b9255 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -89,6 +89,9 @@ PC Server by default; isolation cannot be claimed before admission is implemente The plugin owns its embedding/index profile. Installation may initialize compatible defaults from the main configuration, without following subsequent changes. Credentials remain deployment configuration. Initially, documents in a Scope share the plugin profile; parsing/chunking may vary by knowledge base. Jobs and result metadata pin the relevant profiles. +Active profile references live in knowledge-base Artifact configuration and must agree across active knowledge bases in a +Scope; new bases inherit that reference. Environment settings are initial defaults, not overrides for existing data. Model +changes require switch_model_and_rebuild for the entire shared Scope, as specified in 8.1. ## 2. OpenDAL, identity, and deduplication @@ -163,6 +166,7 @@ cache is not required initially. | pc_sources | Immutable original references and lineage_only evidence for successful user/deletion operations; no new columns | | pc_artifacts | Knowledge-base configuration, document manifests, immutable revisions | | pc_artifact_heads | Current revision, lifecycle_state, governance_generation | +| pc_scopes | Reuse the existing Scope row for short core transaction serialization; no schema change or task counter in version | | pc_artifact_lineage_sources / pc_artifact_lineage_artifacts | Exact-revision input/operation evidence and base references | | Existing permissions, tags, and references | Shared semantics, without unbounded jobs or member JSON | @@ -242,11 +246,14 @@ putting per-file jobs into its tables. Publication is serial per document, with heartbeats, and updates check the token. New targets supersede old targets; lease recovery rotates the token. SQLite uses its actual transaction/CAS capabilities rather than assuming every backend supports SKIP LOCKED. -After authorization/lifecycle checks, recognize accepted idempotent replays before checking the current base for new requests; -a successful network retry must not fail solely because its original ETag is stale. Terminal jobs never revive. Automatic -bounded retries remain within a job; user retries after terminal failure use a new key/job. Cancellation does not undo a -published result. Edits/removals pin their base and reject conflicting active changes rather than silently queue or rebase. -A failed file does not block the whole Scope. +For ordinary requests, authorization/lifecycle checks precede replay recognition, which precedes current-base checks for new +requests. A successful network retry must not fail solely because its original ETag is stale. The deletion entry point allows +authorized inspection of bounded deleted-target state to finish cleanup instead of rejecting it with generic 410 first. +Terminal jobs never revive. Automatic bounded retries remain within a job; ordinary user retries use a new key/job. Repeated +deletion automatically creates successor cleanup jobs as specified in section 7. Cancellation cannot undo publication or any +committed deletion tombstone/retirement; cancelled edges in the state machine are conditional on this cutoff. +Edits/removals pin their base and reject conflicting active changes rather than silently queue or rebase. A failed file does +not block the whole Scope. ## 6. Acceptance, publication, and cross-store recovery @@ -263,17 +270,27 @@ commit. | Short core publication transaction | Check base, ownership, and execution eligibility; write document revision, required operation evidence Source, lineage, and head | | Plugin completion transaction | Record actual result_revision and succeeded; reconcile applied_job_id/result_id after lost acknowledgement rather than republish | -Publication, deletion, target replacement, cancellation, and lease recovery must share a commit-eligibility gate. During short -publication, lock/validate the relevant plugin resource/job records through completion of the core commit. The constrained -writer also checks the knowledge-base head, document base, and lifecycle. Use a fixed lock order; no model calls, index builds, -or DDL inside the gate. Releasing plugin locks before core revision CAS would allow an obsolete token or deleted Source to -publish. Parent deletion must also serialize with the publication parent-state check, not merely an early task-start check. +Core provides the commit gate using the existing `pc_scopes` row. OceanBase/SeekDB use a row lock in the same core transaction; +SQLite uses a core-database `BEGIN IMMEDIATE` write transaction. No lock table or Scope field is added. Publication, deletion, +new-target acceptance, cancellation, execution-token claim/replacement, lease recovery, and model-switch control all acquire +this gate before plugin resource/job locks and then Artifact heads. Ordinary heartbeats only renew the matching token without +transferring ownership. Ingestion and synchronous Artifact mutation entry points must obey the gate too. -If core succeeds but the plugin transaction fails, recovery first reconciles the determined result in the manifest/lineage. -Target replacement and cancellation also reconcile first so that a published success is not recorded as cancellation. -Prepared results are never overwritten; recomputation producing different content uses a new result_id. Failed publication -keeps the old head and its searchable index. Validate these short transactions and lock order on all three backends without -introducing or pretending to provide distributed atomic transactions. +After obtaining both sides' locks, reread target, token, lease, Source markers, parent lifecycle, and already-published core +results. Publication uses the very same core connection/transaction holding the Scope lock, never another unlocked connection. +Cancellation/target replacement/reclaim reconcile inside the gate, commit plugin state, then release the core lock. Publication +commits core first and records plugin success afterward; missing acknowledgement is reconciled. These are separate commits, +not a cross-store atomic transaction. + +Losing the plugin database connection does not release the core lock, so another executor cannot cancel or reclaim meanwhile. +Losing the core connection prevents that transaction from publishing. Any connection error or uncertain commit outcome ends +the attempt; automatic reconnect must not reuse old eligibility. Recovery obtains a fresh core gate before reconciliation and +plugin-state validation. Every control path follows core-before-plugin lock order; never wait for core while holding plugin locks. + +Only short commits within a Scope are serialized. Parsing, OCR, embedding, index construction, and directory enumeration run +concurrently outside the gate; no model calls, DDL, or long computation occurs inside it. Verify actual backend locks, +connection failures, and timeouts rather than substituting memory locks or a one-time token check. Prepared output is immutable; +different recomputation uses a new result_id. Ordinary publication failures retain the old head and usable old index. ## 7. Operation evidence, editing, and soft deletion @@ -288,7 +305,7 @@ Jobs record intent/execution; operation Sources record success, linked through j | Parse/reprocess document | Publish a revision under the same document ID with original lineage; retain evidence for user-triggered changes | | Edit/remove chunk | Increment document revision, produce a complete result, link successful operation evidence, retain previous rows | | Delete document/knowledge-base | Create a deletion revision with a bounded deletion summary and retire the head in the same core transaction; link deletion evidence | -| Delete original Source | Mark the source resource; cancel dependent work; if the current document depends on it, perform recoverable document deletion with evidence | +| Delete original Source | Mark the source resource and immediately deny original/derived reads; finish document retirement, deletion evidence, and index cleanup asynchronously | Deletion revisions are a plugin convention, not a change to other families' governance. A deletion revision may reuse the previous result_id without copying chunk bodies. Its operation summary must actually create a revision rather than be skipped @@ -302,17 +319,44 @@ result with no current retrieval hits. Duplicate import cannot overwrite manual Knowledge-base deletion first commits its deletion revision/retirement, immediately hiding all children. An accepted cleanup job survives restart, marks Sources, deletes documents, and cancels processing in batches. Each changed Artifact gets its own evidence, sharing an operation ID for the cascade. Cleanup is allowed under a deleted parent and is not cancelled by ordinary -processing parent checks. Its persisted cursor is plugin batch progress only. Persist the deletion/cleanup job before retiring the parent so cascade work cannot be lost. +processing parent checks. Its cursor is plugin batch progress only. Persist the deletion/cleanup job before the first deletion +effect. Once a Source tombstone or Artifact retirement commits, deletion is non-cancellable: failures require completion or +recovery rather than reporting cancellation with unfinished side effects. Queued deletion without effects remains cancellable. Deleting a document leaves its original Source readable. Deleting an unpublished replacement Source preserves an old result based on another original. If S1 supplied an old revision and S2 supplied a complete reparse, deleting S1 preserves the current -version based only on S2 but blocks history that depends on S1. Resource markers and Artifact retirement may finish in stages; -reads check applicable parent, document, exact root, and Source markers without waiting for index cleanup. Generic Source, +version based only on S2 but blocks history that depends on S1. A Source deletion response acknowledging an effective deletion, +including 202 cleanup pending, requires a committed tombstone; job acceptance alone is not deletion. That tombstone is the visibility cutoff for +that original and its derived content. Reads/retrieval starting afterward must check it even when the document head is still +active or index entries remain. Content already returned before deletion is not recalled. Only document retirement, +deletion revision/evidence, and index maintenance may be eventually consistent; content must not remain readable while cleanup +is pending. Fail closed when visibility checks are unavailable. Resource markers and retirement may finish in stages, with +reads checking applicable parent, document, exact root, and Source markers. Generic Source, exact/historical Artifact, and evidence reads require framework visibility extension points; plugin search filtering alone does not satisfy deletion. Missing ownership registration fails closed rather than returning unguarded content. Controlled internal recovery may inspect retired history for reconciliation; an authorized management route may expose bounded cleanup status after deletion without exposing bodies or a public bypass parameter. +Repeated deletion uses the same deletion entry point/operation, without a repair/retry API. After authorization, inspect the +original deletion and cleanup state even for a deleted target. A deletion marker or the original stale ETag does not prevent +cleanup; still-active targets retain ordinary preconditions. Conflicting parameters under an idempotency key still return 409. + +The cleanup rules below apply after deletion effects exist. If the initial deletion failed or was cancelled before taking effect, +a repeated deletion accepts a new deletion job under ordinary preconditions; the same idempotency key still replays its original receipt. + +| State when deletion is repeated | Result and action | +| --- | --- | +| Initial deletion or cleanup job remains active | Return the same deletion-operation identity and current job, 202; no duplicate | +| Cleanup incomplete and previous job failed/terminated | Create a new background cleanup job with parent_job_id referring to the original deletion job, 202; never revive the old job | +| Cleanup complete | Return 200 already_deleted; no new job, revision, or evidence | + +Serialize this check and successor creation under the core Scope gate so concurrent repeated deletes cannot create multiple +active cleanup jobs. The internal job uses a fresh derived idempotency key while the client's deletion identity/input remains +unchanged. Responses may refresh cleanup_job_id/status while referring to the same deletion operation. Reconcile tombstones, +Artifact deletion summaries, and the original operation ID; skip completed objects and generate revisions/evidence only for +Artifacts not yet changed. This applies to Sources, documents, and knowledge bases. A deleted parent permits authorized cleanup, +not ordinary writes or content reads. + ## 8. APIs and retrieval Reuse Source encoding/identity/validation; Artifact CRUD/history/tags; authentication; permissions; ETags; pagination; @@ -328,9 +372,10 @@ Routes are proposed contracts. Plugin APIs follow #2579; registration syntax fol | Create knowledge base | POST `/v1/scopes/{s}/artifacts`, family=knowledge-base | | Knowledge-base/document overview and history | Generic Artifact GET/revisions, bounded manifest | | Import local files/directory | POST `P/imports`, explicit knowledge_base_id, root/paths, idempotency_key; 202 job receipt | -| Reprocess/edit/delete/cleanup | POST `P/jobs`, typed operation, pinned target and preconditions; cleanup is internal-only; the same service handles existing synchronous deletion/governance entry points | +| Reprocess/edit/delete | POST `P/jobs`, typed operation, pinned target and preconditions; repeating delete_source/delete_document/delete_knowledge_base repairs cleanup automatically; cleanup is internal-only | +| Change model and rebuild index | POST `P/jobs`, operation=switch_model_and_rebuild, explicit confirmation of Scope-wide impact; existing job status APIs | | Job list/detail | GET `P/jobs`, GET `P/jobs/{job_id}`, pagination, stage, state, bounded error, successful revision | -| Cancel | POST `P/jobs/{job_id}/cancel`, unpublished nonterminal work only | +| Cancel | POST `P/jobs/{job_id}/cancel`, nonterminal work without publication or committed deletion effects; model switching is also non-cancellable after publication starts | | Chunk directory | GET `P/documents/{d}/revisions/{rev}/chunks`, paged metadata without body | | Single chunk | Append `/{chunk_id}`, body, provenance, edit metadata | | Batch chunks | Append `/batch-get`, POST bounded chunk_ids | @@ -392,8 +437,8 @@ Retrieval limit counts chunks; optional snippets are bounded and bodies use chun Artifacts rather than chunk responses. Index candidates must match the current manifest result_id and index profile and pass ownership, authorization, and deletion checks. Refill after filtering so invalid candidates do not consume top-k. The adapter covers initial writes, revision replacement, rebuild, coverage/digest validation, zero chunks, deletion filtering, and locators. -Historical bodies do not require every historical search index. Rebuild may pause publication, but new content cannot publish -without its required index; retain the usable old index until replacement publication. +Historical bodies do not require every historical search index. Same-profile rebuild retains the usable old index and cannot +publish content missing its required index. Model changes use the controlled maintenance procedure in 8.1. Same-Scope retrieval may select multiple knowledge bases. Cross-Scope helpers authorize each explicit target, call the same per-Scope API, fuse ranks, and preserve target identity/errors rather than compare incompatible vector-space scores. Reject @@ -401,6 +446,47 @@ unsupported filters/rerank options. Python/MCP use the same service. Reuse Scope permissions, checking every affected object. Acceptance uses 428/412 preconditions, 409 conflicts, 410 deletion, 422 validation, 413 limits, and 503 unavailability. After 202, failures are durable job states rather than conclusions inferred from logs. +### 8.1 Change model and rebuild the index + +Existing data's active model, dimensions, and embedding parameters cannot be overwritten through configuration PUT, environment +refresh, or restart. Use `switch_model_and_rebuild` with a pinned target_profile identifying model/version, dimensions, complete +embedding-input rules, and index configuration; credentials remain configuration references. Because a Scope shares one profile, +the operation requires Scope administration and explicit confirmation of all its knowledge bases, not merely the initiating base. + +```json +{"knowledge_base_id":"ops","operation":"switch_model_and_rebuild","idempotency_key":"model-switch-01","input":{"expected_profile_id":"embedding-v1","target_profile_id":"embedding-v2","confirm_scope_wide":true}} +``` + +Reuse jobs' input_snapshot, checkpoint, parent_job_id, and document child jobs for old/target profiles, phase, and rebuild progress; +no control table is added. The Scope gate permits one unfinished switch operation per Scope. Durable checkpoint phases are +preparing, rebuilding, publishing, completed, aborted. Failure/process exit does not automatically clear maintenance; running job state +alone must not decide whether service is paused. Resolve maintenance from the latest effective checkpoint in the original switch +and successor chain: successor completed/aborted closes the operation while old failed records remain as history, not blockers. + +| Phase | Behavior | +| --- | --- | +| Acceptance/preparing | Persist switch job and old/target profiles; pause Scope retrieval and ordinary writes/publication, retain management status and exact content reads; finish cleanup for deletions already in effect | +| rebuilding | Pin current valid document revisions, build isolated target-profile indexes from committed chunks without OCR, validate counts/digests, dimensions, and complete-input token limits | +| publishing | Publish document revisions changing only index-profile references, reusing body result_id where appropriate, with success evidence; update all active knowledge-base configuration revisions | +| completed | Verify all valid documents, knowledge-base configuration, and target indexes agree; complete under the gate and release maintenance so queries and subsequent jobs use the target profile together | + +Retrieval/ordinary writes return explicit 503 with the switch job reference during maintenance, never mixed-model results or +silent empty results. Knowledge-base creation also checks maintenance. Repeated deletion/cleanup for effects already committed +remains allowed so failed cleanup cannot deadlock preparation; new deletion requests are paused ordinary writes. +Old-profile unpublished jobs cannot commit: freeze their +eligibility and reconcile; mark unpublished old targets superseded without rewriting their inputs, and let callers submit new +requests when needed. Queries pin their profile and recheck maintenance/active profile before returning; a change yields 503 +rather than an in-flight old-model result. Exact chunk/history reads still use fixed result_id and deletion guards. Retain old indexes at least until +switch success. + +In preparing/rebuilding, cancellation/failure restores old-profile service only after verifying under the gate that no profile +revision was published and persisting aborted. Failed job state alone never releases maintenance; superseded jobs do not revive. Once publication starts, cancellation/automatic rollback is forbidden because +some objects may already use the target. Maintain the pause and complete forward recovery. Repeating switch_model_and_rebuild +with the same target and a new request key may create a successor job linked to the original switch, skipping already-published +revisions without reviving failed jobs or duplicating evidence. The same request key returns its existing job. Reject a different +target while a switch remains unfinished. Insufficient input budget in the new model fails explicitly and requires rechunking +first; never silently truncate. Neither distributed atomic commits nor uninterrupted switching are required. + ## 9. Implementation and acceptance Only plugin storage needs new migrations; existing core tables receive no new fields/migrations. The plugin framework must @@ -417,9 +503,14 @@ Verify on SQLite, SeekDB, and OceanBase: and cancellation. - Prepared output followed by core rollback; core success followed by lost task acknowledgement; old content availability, invisible uncommitted results, and no duplicate publication. +- Loss of only the plugin connection, loss of only the core connection, uncertain commit outcomes, cancellation/reclaim races, + and the core Scope gate preventing old-transaction reconnect/publication. - Creation/modification/deletion evidence tied to actual revisions; increment on chunk removal, readable zero chunks, history. -- Source/document/knowledge-base deletion racing publication, recoverable cascade, and all ordinary/exact/historical/evidence - read guards. +- Source/document/knowledge-base deletion racing publication; tombstones deny derived reads before head/index cleanup. +- Cancellation rejected after deletion effects; repeated deletes repair failed cleanup, concurrent retries share one active + successor, and completed objects do not get duplicate revisions/evidence. +- Direct active-model configuration edits rejected, Scope-wide switch/rebuild, partial-publication recovery, failed maintenance, + and old-profile job invalidation. - Directory/single/batch chunk boundaries, complete index lifecycle, rebuild, and valid-candidate refill. - OpenDAL snapshots accessible to Server/Worker; later original changes do not change accepted inputs. @@ -460,8 +551,9 @@ does not automatically provide Source cascades or plugin lifecycle guards. # Unresolved questions -Before implementation, fix composite registration/constrained writer signatures, backend lock order for publication/deletion -gates, generic read guards, and exclusive Source consumption admission. Implementation fixes OCR models, chunking defaults, +Before implementation, fix composite registration/constrained writer interfaces for the core Scope gate, generic read guards, +and exclusive Source consumption admission. Lock order is core Scope, plugin resources/jobs, then Artifact heads; backend +adapters must verify connection failures and compatibility with existing generic mutation paths. Implementation fixes OCR models, chunking defaults, lease/concurrency/retry limits, API count/byte bounds, and concrete schema types without changing ownership or commit semantics. Restoration/erasure, job archival and idempotency retention, rename identity, per-base vector spaces, and full edited-document export require separate contracts. diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index 323df8dd6a..122c0f8a19 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -75,6 +75,8 @@ Scope 保持授权边界。知识库 Scope 的业务内容只包括文档 Source 插件独立持有 embedding/索引配置,可在安装时从兼容主路径初始化,此后不自动跟随。密钥保持在部署配置中。 首期同一 Scope 的 document 共用插件 profile,解析/切块可按知识库配置;模型和索引配置固定进任务及结果元数据。 +当前 profile 引用保存在 knowledge-base Artifact 配置,同 Scope 的有效知识库必须一致,新建知识库继承该引用。 +环境变量只提供初始默认值,不能覆盖已有数据的活动 profile。更换模型只能执行 switch_model_and_rebuild,覆盖整个共享 Scope,见 8.1。 ## 2. OpenDAL、身份与去重 @@ -136,6 +138,7 @@ Markdown 使用 markdown-it-py 提取结构和来源映射。图片使用 RapidO | pc_sources | 不可变原文引用、成功人工/删除操作的 lineage_only 证据;不增加列 | | pc_artifacts | knowledge-base 配置、document manifest、不可变 revision | | pc_artifact_heads | 当前 revision、lifecycle_state、governance_generation | +| pc_scopes | 复用既有 Scope 行作为 core 短事务互斥点,不改字段或借用 version 作为任务计数 | | pc_artifact_lineage_sources/pc_artifact_lineage_artifacts | 精确版本的输入/操作证据和 base 引用 | | 既有权限、tags 和引用设施 | 复用公共语义,不承载无界任务或成员 JSON | @@ -204,8 +207,10 @@ KnowledgeBaseTaskSupervisor 只扫描插件 jobs,负责领取、心跳、过 `target_generation` 表示用户期望哪个结果,`execution_token` 表示同一任务哪次执行拥有资格。领取、续租和状态更新均条件校验 token; 新目标使旧目标 superseded,租约恢复更换 token。SQLite 使用实际支持的事务/CAS,不假设所有后端均支持 SKIP LOCKED。 -同键重放在授权及生命周期检查后先识别已接受任务,再检查新请求的当前 base,避免成功重试被旧 ETag 拒绝。 -终态任务不复活;自动有限重试属于同一任务,用户重新执行失败任务使用新幂等键创建新 job。取消不回滚已发布结果。 +普通请求在授权及生命周期检查后先识别同键重放,再检查新请求的当前 base,避免成功重试被旧 ETag 拒绝。 +删除入口允许授权调用者再次访问已删除目标的有限状态以补齐清理,不能先用通用 410 阻断该入口。 +终态任务不复活;自动有限重试属于同一任务,普通处理的人工重试使用新幂等键/job。删除善后按第 7 节由再次删除自动创建新 job。 +取消不回滚已发布结果;任何删除墓碑或 retirement 一经提交,相关删除/善后工作不可取消。状态机的 cancelled 边受此条件约束。 编辑/移除固定 base,有冲突的活跃变更时拒绝,不静默排队或换基准。逐文件失败不阻塞整个 Scope。 ## 6. 接受、发布与跨存储恢复 @@ -222,14 +227,22 @@ Core 与插件专属存储不共享事务,不能声称 Source、任务、chunk | Core 发布短事务 | 校验 base、归属和执行资格;提交 document revision、必要操作证据 Source、lineage 和 head | | 插件完成事务 | 写实际 result_revision 和 succeeded;若确认丢失,按 applied_job_id/result_id 对账,不重复发布 | -发布、删除、换目标、取消和租约回收必须共享提交资格闸门。短发布期间,插件锁定/校验相关资源与任务记录并保持到 core 提交结束, -同时通过受限 writer 校验知识库 head、document base 和生命周期。锁顺序固定,不在闸门内做模型调用、索引构建或 DDL。 -不能先释放插件锁再仅凭 core revision CAS 发布,否则旧 token/已删除 Source 仍可能提交。 -父知识库删除还须与发布的父状态检查互斥,不能只在任务开始检查。 +提交闸门由 core 提供,复用 `pc_scopes` 中已存在的 Scope 行。OceanBase/SeekDB 使用同一 core 事务中的行锁, +SQLite 使用 core 数据库的 `BEGIN IMMEDIATE` 写事务;不新增锁表、不改 Scope 字段。发布、删除、接受新目标、取消、 +领取/更换执行 token、租约回收及模型切换控制都必须先取得该闸门,再按固定顺序锁定插件资源/job,最后操作 Artifact head。 +普通心跳只按 token 续租,不改变执行所有权;接入和同步 Artifact 修改入口也不得绕过闸门。 -Core 成功后插件事务失败,恢复者先查 manifest/lineage 的确定结果;在改变目标或取消前也做对账,不能把已发布成功记为取消。 -准备好的结果永久不可原地覆盖;重新计算不同内容使用新 result_id。发布失败保留旧 head 和旧结果的可检索索引。 -首期在三种后端验证这些短事务与锁的顺序;不引入分布式事务,也不伪装跨库原子性。 +取得两侧锁后重新读取目标、token、租约、Source 墓碑、父知识库生命周期和 core 已发布结果。发布始终在持有 Scope 锁的同一 core +连接/事务中完成,不能转交另一个无锁连接。取消/换目标/重领先在闸门内对账,再提交插件状态,完成后才释放 core 锁。 +发布路径则先提交 core,再补记插件成功;补记失败按确定结果恢复。这仍是分开提交,不是跨库原子事务。 + +插件数据库连接丢失时,core 锁仍阻止另一执行者取消或重领;core 连接丢失时,该事务不能再用于发布。 +任一连接报错或提交结果不确定,都退出当前尝试,禁止自动重连后沿用旧资格。恢复必须新取 core 闸门,再对账、重验插件状态。 +所有控制路径都遵循 core 在前、插件在后的锁顺序;不能在持有插件锁时反向等待 core 闸门。 + +该方案将同 Scope 的短提交串行化;解析、OCR、向量计算、索引构建和目录枚举在锁外并发进行。 +闸门内不做模型调用、DDL 或长时间计算。三种后端验证真实锁/连接失效和超时行为,不用内存锁或仅一次 token 检查替代。 +准备结果不可原地覆盖;重算不同内容使用新 result_id。普通发布失败保留旧 head 和可用旧索引。 ## 7. 操作证据、编辑与软删除 @@ -243,7 +256,7 @@ Core 成功后插件事务失败,恢复者先查 manifest/lineage 的确定 | 解析/重解析 document | 同 document ID 发布新 revision,lineage 关联原文;人工触发的变更保留操作证据 | | 编辑 chunk/移除 chunk | document revision +1,完整新结果;关联成功操作证据,旧行不删 | | 删除 document/knowledge-base | 新增含有界删除摘要的删除 revision,并在同一个 core 事务 retire head;关联删除证据 | -| 删除原文 Source | 标记 source 资源;取消依赖任务,当前 document 仍依赖它时执行可恢复的 document 删除并生成证据 | +| 删除原文 Source | 标记 source 资源后立即阻断其原文及派生内容读取;document retirement、删除证据和索引清理由后台最终补齐 | 删除整个 Artifact 生成 revision 是本插件的业务约定,不改变其他 family 的治理规则。删除 revision 可复用之前的 result_id, 无需复制 chunk 正文。操作摘要必须使删除 revision 真正写入,不能被“相同 content 的 put 是 no-op”跳过。 @@ -254,14 +267,36 @@ Core 成功后插件事务失败,恢复者先查 manifest/lineage 的确定 删除 knowledge-base 先提交父对象删除 revision/retirement,立即阻断全部子内容;接受的 cleanup job 可在进程重启后继续, 分批标记 Source、删除 document、取消处理任务。每个真正变化的 Artifact 生成自己的证据,使用共同 operation ID 关联级联。 -Cleanup 是已删除父对象下的允许操作,不能被普通处理任务的父状态检查取消。已接受清理任务的固定游标只用于插件分批操作。接受删除时先持久保存删除/清理 job,再退休父对象,避免丢失级联工作。 +Cleanup 是已删除父对象下的允许操作,不能被普通处理任务的父状态检查取消。清理游标只用于插件分批操作。 +先持久接受删除/清理 job,再提交第一个删除标记。Source 墓碑或 Artifact retirement 一旦提交,删除进入不可取消阶段; +后续错误只能恢复善后,不能报告“已取消”并遗留半完成删除。尚未产生删除效果的排队任务仍可取消。 删除 document 保留原文 Source 可读;原文读取不因 document 单独删除而失效。删除未发布替代 Source 保留基于其他原文的旧版本。 S1 对应旧 revision、S2 对应完整新解析时,删除 S1 不删除仅依赖 S2 的当前版本,但依赖 S1 的历史读取失效。 -资源标记与 Artifact retirement 可分阶段完成,读取必须同时检查适用的父对象、document、精确 root 和 Source 标记,不能等待索引清理。 +Source 删除入口返回已生效回执(包括 202 清理中)前必须提交墓碑;仅接受 job 不等于已经删除。 +Source 墓碑提交是该原文及其派生内容的可见性截止点。此后开始的 document/chunk/历史/证据读取和检索都必须检查墓碑, +即使 document head 仍 active 或索引条目还在,也不能返回对应内容。删除开始前已返回给客户端的内容不作撤回保证。 +只允许 document retirement、删除 revision/证据及索引维护最终一致,不允许在等待后台清理时继续暴露内容;检查服务不可用时关闭读取。 +资源标记与 Artifact retirement 可分阶段完成,读取同时检查适用的父对象、document、精确 root 和 Source 标记。 通用 Source、Artifact 精确/历史和证据读取需要框架可见性扩展点;仅插件检索过滤不满足删除契约。归属登记缺失时拒绝读取,不回退为无约束内容。 受控内部恢复可以读取 retired 历史以对账;授权管理入口可查看删除后清理任务的有限状态,不开放正文或公共绕过参数。 +再次删除复用同一个删除入口/operation,不新增 repair/retry API。鉴权后允许检查已删除目标的原删除记录和清理状态, +不因删除标记或原来的 ETag 已过时而直接拒绝善后;尚未删除的目标仍执行正常前置条件。重复请求参数冲突仍返回 409。 + +以下善后规则针对已经产生删除效果的操作。若首次删除在生效前失败或取消,再次删除按正常前置条件接受新删除任务;同幂等键仍重放原回执。 + +| 再次删除时的状态 | 返回和动作 | +| --- | --- | +| 首次删除或清理 job 仍活跃 | 返回同一删除操作标识与当前 job,202;不重复创建 | +| 清理未完成、上一次 job 已 failed/终止 | 后台创建新的 cleanup job,parent_job_id 关联原删除 job,202;旧任务不复活 | +| 所有清理已完成 | 200 already_deleted;不新增任务、revision 或证据 | + +在 core Scope 闸门内串行检查和创建后继任务,避免并发重复删除产生多个善后任务。新的内部 job 使用新的派生幂等键, +原客户端删除请求的身份和输入不变;响应可更新 cleanup_job_id/状态,但稳定关联同一次删除操作。 +清理按已提交墓碑、Artifact 删除摘要和原 operation ID 对账,跳过已完成对象;只为尚未实际修改的 Artifact 生成删除 revision/证据。 +该规则覆盖 Source、document 和 knowledge-base。已删除父对象仅允许这些受授权善后行为,不恢复普通写入或内容读取。 + ## 8. 接口与检索 复用 Source 编码/身份/校验、Artifact CRUD/history/tags、认证、权限、ETag、分页、引用与错误封装。 @@ -276,9 +311,10 @@ S1 对应旧 revision、S2 对应完整新解析时,删除 S1 不删除仅依 | 创建知识库 | POST `/v1/scopes/{s}/artifacts`,family=knowledge-base | | 知识库/document 概览与历史 | 通用 Artifact GET/revisions,返回有界 manifest | | 导入本地文件/目录 | POST `P/imports`,显式 knowledge_base_id、root/paths 和 idempotency_key;202 任务回执 | -| 重解析/编辑/删除/清理 | POST `P/jobs`,类型化 operation、固定目标和前置条件;cleanup 仅供内部使用,同一业务服务负责现有同步删除/治理入口 | +| 重解析/编辑/删除 | POST `P/jobs`,类型化 operation、固定目标和前置条件;再次 delete_source/delete_document/delete_knowledge_base 自动补齐清理,cleanup 仅供内部使用 | +| 更换模型并重建索引 | POST `P/jobs`,operation=switch_model_and_rebuild,显式确认同 Scope 的影响范围;复用任务状态接口 | | 任务列表/详情 | GET `P/jobs`、GET `P/jobs/{job_id}`,分页、阶段、状态、有界错误、成功 revision | -| 取消 | POST `P/jobs/{job_id}/cancel`,仅未发布非终态工作 | +| 取消 | POST `P/jobs/{job_id}/cancel`,仅未发布且未提交删除效果的非终态工作;模型切换发布开始后也不可取消 | | chunk 目录 | GET `P/documents/{d}/revisions/{rev}/chunks`,分页元数据,不含正文 | | 单个 chunk | 上述路径追加 `/{chunk_id}`,正文、出处、人工修改信息 | | 批量 chunk | 上述路径追加 `/batch-get`,POST 有界 chunk_ids | @@ -336,13 +372,48 @@ Batch-get 要求非空、无重复 ID,按请求顺序返回;先授权父对 检索 limit 计 chunk 数;可选 snippet 有界,正文从 chunk 接口获取。通用 Artifact search 继续返回 Artifact,不混入 chunk 响应。 索引命中必须对应当前 manifest 的 result_id 和索引 profile,并满足归属、权限及删除规则;过滤后继续补取候选,避免无效结果占满 top-k。 适配覆盖首次写入、版本替换、重建、coverage/摘要核对、零块、删除过滤和命中定位。保留历史正文不要求保留所有历史索引。 -重建可暂停发布,但不能发布缺失所需索引的新内容;旧可用索引在替代结果发布前保留。 +同 profile 重建保留旧可用索引,不能发布缺少所需索引的新内容;模型切换走 8.1 的受控维护流程。 同 Scope 可选择多个知识库;跨 Scope helper 逐个授权显式目标,调用同一分 Scope 接口,融合排名并保留目标身份/错误, 不直接比较不兼容向量空间的原始分数。不支持的 filter/rerank 明确拒绝。Python/MCP 复用同一业务服务。 权限复用 Scope 读/贡献和 Artifact 写/治理能力,跨对象请求逐个检查。接受失败沿用 428/412 前置条件、409 冲突、410 已删除、 422 校验、413 大小限制和 503 不可用;202 后的失败记录在任务状态中,不再靠日志推测。 +### 8.1 更换模型并重建索引 + +已有数据的活动模型、维度和 embedding 参数不能通过配置 PUT、环境变量刷新或重启直接覆盖。 +只能执行 `switch_model_and_rebuild`;target_profile 固定模型身份/版本、维度、完整 embedding 输入规则和索引配置,密钥仍只保存配置引用。 +由于首期同 Scope 共用 profile,操作需 Scope 管理权限,并确认影响整个 Scope 的知识库;不能声称只修改发起请求的一个知识库。 + +```json +{"knowledge_base_id":"ops","operation":"switch_model_and_rebuild","idempotency_key":"model-switch-01","input":{"expected_profile_id":"embedding-v1","target_profile_id":"embedding-v2","confirm_scope_wide":true}} +``` + +复用 jobs 的 input_snapshot、checkpoint、parent_job_id 和逐文档子任务保存旧/目标 profile、阶段和重建进度,不新增控制表。 +Scope 闸门保证同 Scope 只有一个未完成的切换操作。其持久 checkpoint 阶段为 preparing、rebuilding、publishing、completed、aborted; +失败/进程退出不会自动清除维护状态,不能只用 job 是否 running 判断是否暂停。 +按原切换操作及后继任务链的最新有效 checkpoint 判定维护;后继 completed/aborted 可以关闭该操作,旧 failed 记录保留但不单独继续阻断。 + +| 阶段 | 行为 | +| --- | --- | +| 接受/preparing | 持久保存切换任务及旧/目标配置;暂停该 Scope 的检索和普通写入/发布,保留管理状态及精确内容读取;先完成已生效删除的善后 | +| rebuilding | 固定当前有效 document 版本,从已提交 chunks 构建目标 profile 的隔离索引,不重复 OCR;验证数量/摘要、维度和完整输入 token 上限 | +| publishing | 逐文档发布仅更新索引 profile 引用的新 revision,正文 result_id 可复用;写成功操作证据;同步更新所有有效 knowledge-base 的配置 revision | +| completed | 核验全部有效文档、知识库配置与目标索引一致,再在闸门内确认完成并解除维护;查询与后续任务一起使用目标 profile | + +检索/普通写入在维护期明确返回 503 和切换任务引用,不能返回混合模型结果或静默空结果。新建知识库也参与维护检查。 +已生效删除的再次删除/善后不被维护阻断,避免清理失败后无法继续准备切换;新删除请求属于暂停的普通写入。 +切换前的旧 profile 待发布任务不得继续提交:冻结其执行资格并对账,未发布的旧目标标记 superseded,输入不原地改写;需要时由调用者提交新请求。 +查询固定本次 profile,返回前复核维护状态及活动 profile;若期间改变,返回 503,不返回在途旧模型结果。 +精确 chunk/历史读取仍使用固定 result_id,并照常执行删除检查。旧索引至少保留到切换成功。 + +在 preparing/rebuilding 阶段,取消或失败后须在闸门内确认没有 profile revision 发布,再持久记录 aborted 并恢复旧 profile 服务; +不能仅因任务 failed 就解除维护。原来已 superseded 的任务不自动复活。 +一旦开始发布,禁止取消/自动退回旧配置:部分对象可能已切换,必须保持维护并向前补齐。 +调用同一个 switch_model_and_rebuild 操作、相同目标 profile 和新的请求键可创建后继任务,关联原切换操作并跳过已完成 revision, +不复活失败任务、不重复成功证据。相同请求键只返回已有任务;未完成切换期间拒绝不同目标模型。 +若新模型输入预算不足,重建失败并明确要求先调整切块,不静默截断。全程不要求跨数据库原子提交或无停机切换。 + ## 9. 实施与验收 仅新增插件存储迁移,已有核心表无需新增字段/迁移。插件框架需提供能力注册、消费准入、受限发布和可见性检查; @@ -355,8 +426,11 @@ SQLite、SeekDB、OceanBase 都验证: - 同请求重放、不同参数冲突、同目标活跃冲突、内容去重、配置重解析和人工编辑保护。 - 任务接受后退出、Source 已登记但未确认、租约重领、迟到 token、目标替换、有限重试和取消。 - 结果准备后 core 回滚、core 成功但任务确认失败;旧版本可用、结果不提前可见、不重复发布。 +- 插件连接单独断开、core 连接单独断开、提交响应未知与取消/重领竞争,验证 core Scope 闸门和禁止旧事务重连发布。 - 创建/修改/删除证据与实际 revision 一致;删除 chunk 版本递增、零块可读、历史保留。 -- Source/document/knowledge-base 删除与发布竞争,可恢复级联,所有普通/精确/历史/证据读取阻断。 +- Source/document/knowledge-base 删除与发布竞争;墓碑已提交但 head/索引未清理时仍拒绝派生内容读取。 +- 删除生效后取消被拒绝,反复删除补齐失败清理,并发重删只产生一个活跃善后 job,已完成对象不重复 revision/证据。 +- 模型配置直接修改被拒绝,Scope 级切换/重建、部分发布后恢复、失败维护和旧 profile 任务失效。 - Chunk 目录/单块/批量边界、索引全生命周期、重建及有效候选补取。 - OpenDAL 本地快照对 Server/Worker 可访问,原文件随后变化不改变已接受输入。 @@ -387,7 +461,8 @@ SQLite、SeekDB、OceanBase 都验证: # 待解决问题 -实现前固定复合插件注册/受限 writer 签名、发布与删除闸门的后端锁顺序、通用读取 guard 接入和 Source 排他消费准入。 +实现前固定复合插件注册/受限 writer 的 core Scope 闸门接口、通用读取 guard 接入和 Source 排他消费准入。 +锁顺序遵循 core Scope、插件资源/job、Artifact head,后端适配需验证连接失效和已有通用写入路径兼容性。 实现时固定 OCR 模型、切块参数、任务租约/并发/重试限额、API 数量/字节上限及 schema 具体类型。这些不改变本文的数据归属和提交语义。 恢复/擦除、任务归档幂等保留期、改名身份、逐知识库向量空间与完整编辑文档导出另定契约。 From 71e842cd2a34a7943ab0adecb3542771e3da387e Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Wed, 11 Nov 2026 21:52:53 +0800 Subject: [PATCH 09/13] docs(rfc): define deletion before first document publication --- docs/en/rfcs/2570-knowledge-base.md | 15 ++++++++++++++- docs/zh/rfcs/2570-knowledge-base.md | 11 ++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index f37d8b9255..b70e31f3af 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -312,6 +312,17 @@ previous result_id without copying chunk bodies. Its operation summary must actu by an identical-content put no-op. Evidence, lineage, revision, and head commit together in core; failure creates no success evidence, and replaying the same accepted operation does not add revisions. +Deletion must distinguish a published document from a logical file that has never published an Artifact. Under the existing +core Scope gate and plugin resource/job locks, reread the head and reconcile publication before selecting the branch. If a head +exists, use the revision/retirement protocol above. If the file has never published, deleting it marks its document resource +and invalidates pending publication; no Artifact ETag, empty Artifact, deletion revision, or Artifact-success evidence is required. +Knowledge-base cascades include these unpublished resources. Source deletion marks the selected Source and invalidates only +work depending on it; it does not retire a nonexistent document or delete unrelated Source versions. Direct document deletion +still leaves original Sources readable. Missing heads for previously published files are consistency errors, not this branch. +The resource tombstone and invalidation commit before releasing the gate, so a concurrent first publication cannot slip through. +The job records completion; repeated deletion succeeds without inventing an Artifact operation. A committed resource tombstone +is a deletion effect and prevents cancellation, even when no Artifact exists. + Manual text replacement may retain a logical chunk ID, but references include a revision. Rechunking may create new IDs. Edited text is marked non-verbatim with original locators and edit provenance. Removing the last chunk permits a zero-chunk result with no current retrieval hits. Duplicate import cannot overwrite manual edits; explicit reprocessing requires discard. @@ -320,7 +331,7 @@ Knowledge-base deletion first commits its deletion revision/retirement, immediat job survives restart, marks Sources, deletes documents, and cancels processing in batches. Each changed Artifact gets its own evidence, sharing an operation ID for the cascade. Cleanup is allowed under a deleted parent and is not cancelled by ordinary processing parent checks. Its cursor is plugin batch progress only. Persist the deletion/cleanup job before the first deletion -effect. Once a Source tombstone or Artifact retirement commits, deletion is non-cancellable: failures require completion or +effect. Once a resource tombstone or Artifact retirement commits, deletion is non-cancellable: failures require completion or recovery rather than reporting cancellation with unfinished side effects. Queued deletion without effects remains cancellable. Deleting a document leaves its original Source readable. Deleting an unpublished replacement Source preserves an old result @@ -507,6 +518,8 @@ Verify on SQLite, SeekDB, and OceanBase: and the core Scope gate preventing old-transaction reconnect/publication. - Creation/modification/deletion evidence tied to actual revisions; increment on chunk removal, readable zero chunks, history. - Source/document/knowledge-base deletion racing publication; tombstones deny derived reads before head/index cleanup. +- Delete a first-import queued/failed file without an Artifact, cascade over unpublished resources, and race deletion against + first publication; no fabricated deletion revision/evidence and no cancellation after a resource tombstone commits. - Cancellation rejected after deletion effects; repeated deletes repair failed cleanup, concurrent retries share one active successor, and completed objects do not get duplicate revisions/evidence. - Direct active-model configuration edits rejected, Scope-wide switch/rebuild, partial-publication recovery, failed maintenance, diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index 122c0f8a19..37f7325856 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -262,13 +262,21 @@ SQLite 使用 core 数据库的 `BEGIN IMMEDIATE` 写事务;不新增锁表、 无需复制 chunk 正文。操作摘要必须使删除 revision 真正写入,不能被“相同 content 的 put 是 no-op”跳过。 证据、lineage、revision、head 在 core 同事务提交;失败不产生成功证据。同一已接受操作重放不增加 revision。 +删除必须区分“已有 document Artifact”和“从未发布 Artifact 的逻辑文件”。在既有 core Scope 闸门及插件资源/job 锁内, +重新读取 head 并对账发布结果后选择分支:已有 head 按上述 revision/retirement 协议处理;确认从未发布时,删除逻辑文件只标记 +其 document 资源并使待发布任务失效,不要求 Artifact ETag,不创建空 Artifact、删除 revision 或 Artifact 成功操作证据。 +知识库级联也必须处理这些未发布资源。删除 Source 只标记指定 Source 并使依赖它的任务失效,不 retire 不存在的 document, +不删除无关 Source 版本;单独删除 document 仍保留原文 Source 可读。曾经发布但 head 缺失属于一致性错误,不能按未发布分支跳过。 +资源墓碑和任务失效须在释放闸门前提交,避免判断无 head 后后台又完成首次发布。Job 记录完成,重复删除不虚构 Artifact 动作。 +资源墓碑一经提交即属于删除生效,即使尚无 Artifact,也不能再取消该删除。 + 手动替换文字可保留逻辑 chunk ID,但引用必须带 revision;重切块可产生新 ID。人工正文标记非原文逐字引用,保留原始定位与编辑依据。 移除最后一块允许零 chunk 结果,当前检索无命中。重复导入不得覆盖人工修改,显式重新解析需要 discard 授权。 删除 knowledge-base 先提交父对象删除 revision/retirement,立即阻断全部子内容;接受的 cleanup job 可在进程重启后继续, 分批标记 Source、删除 document、取消处理任务。每个真正变化的 Artifact 生成自己的证据,使用共同 operation ID 关联级联。 Cleanup 是已删除父对象下的允许操作,不能被普通处理任务的父状态检查取消。清理游标只用于插件分批操作。 -先持久接受删除/清理 job,再提交第一个删除标记。Source 墓碑或 Artifact retirement 一旦提交,删除进入不可取消阶段; +先持久接受删除/清理 job,再提交第一个删除标记。资源墓碑或 Artifact retirement 一旦提交,删除进入不可取消阶段; 后续错误只能恢复善后,不能报告“已取消”并遗留半完成删除。尚未产生删除效果的排队任务仍可取消。 删除 document 保留原文 Source 可读;原文读取不因 document 单独删除而失效。删除未发布替代 Source 保留基于其他原文的旧版本。 @@ -429,6 +437,7 @@ SQLite、SeekDB、OceanBase 都验证: - 插件连接单独断开、core 连接单独断开、提交响应未知与取消/重领竞争,验证 core Scope 闸门和禁止旧事务重连发布。 - 创建/修改/删除证据与实际 revision 一致;删除 chunk 版本递增、零块可读、历史保留。 - Source/document/knowledge-base 删除与发布竞争;墓碑已提交但 head/索引未清理时仍拒绝派生内容读取。 +- 首次导入排队/失败且尚无 Artifact 时删除,知识库级联覆盖未发布资源;与首次发布竞争时不漏删,不虚构删除 revision/证据,资源墓碑提交后不可取消。 - 删除生效后取消被拒绝,反复删除补齐失败清理,并发重删只产生一个活跃善后 job,已完成对象不重复 revision/证据。 - 模型配置直接修改被拒绝,Scope 级切换/重建、部分发布后恢复、失败维护和旧 profile 任务失效。 - Chunk 目录/单块/批量边界、索引全生命周期、重建及有效候选补取。 From 39d8d0c8233561827fd0bbb0a8d6dc2d0a574e66 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Fri, 13 Nov 2026 18:02:18 +0800 Subject: [PATCH 10/13] docs(rfc): align knowledge bases with scope plugin contracts --- docs/en/rfcs/2570-knowledge-base.md | 746 ++++++++++------------------ docs/zh/rfcs/2570-knowledge-base.md | 561 ++++++++------------- 2 files changed, 462 insertions(+), 845 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index b70e31f3af..3e3e01478b 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -1,6 +1,6 @@ --- -title: "RFC 2570: Knowledge Base document plugin" -description: "Provide document knowledge bases with one business plugin, an independent durable queue, and three plugin tables without changing existing Source or Artifact schemas." +title: "RFC 2570: Scope-based Knowledge Base document plugin" +description: "One Scope per knowledge base, framework consumption cursors and document Artifacts, with three database backends, synchronous chunk editing and native soft deletion." --- - Proposal Name: `knowledge_base_plugin` @@ -11,569 +11,355 @@ description: "Provide document knowledge bases with one business plugin, an inde # Summary -One `knowledge-base` business plugin provides local ingestion, parsing, chunking, version management, and hybrid retrieval. -A Scope may contain multiple user-created `knowledge-base` Artifacts. Each original Source and whole-file `document` Artifact -belongs exclusively to one knowledge base. Existing Source, Artifact, head, and lineage schemas remain unchanged; the plugin -adds resource, job, and chunk tables. Background processing does not use the existing Source consumption cursor. This is a -target design dependent on plugin framework extensions, not a statement of released functionality. +One `knowledge-base` business plugin provides local ingestion, parsing, chunking, versioning, and hybrid retrieval. Each +ordinary Scope is one knowledge base. The plugin declares only the `document` family, with one Artifact per complete file. +The knowledge base itself is not an Artifact; plugin storage holds its configuration by scope_id. The plugin supplies original +and processing-request Source definitions and reuses framework generate, Supervisor, and consumption cursors rather than +implementing an independent task scheduler. + +The first phase supports SQLite, SeekDB, OceanBase, Markdown, standalone-image RapidOCR, rule-based chunking, synchronous +chunk edits/removals, and document forget. This is a target design dependent on framework contracts, not a claim that the +current implementation PR provides every capability. # Motivation -Business descriptions and SOPs need faithful originals, passage retrieval, predictable updates, and deletion. Parsing may be -slow or depend on external services, requiring durable work and per-file recovery. A business plugin should own these states -without adding knowledge-base fields to the shared Source model or blocking unrelated files behind one consumption cursor. -Artifacts continue to manage whole-document versions; separate chunks and indexes avoid reading large body JSON values. +Business descriptions and SOPs need searchable passages, original provenance, and manual changes that preserve history. +Scope provides the authorization and organizational boundary, Artifacts manage whole-document revisions, and plugin storage +holds bodies and indexes. Existing scheduling, revision preconditions, and lifecycle rules reduce domain-specific machinery. # Guide-level explanation -1. Create an empty `knowledge-base` through the generic Artifact API, then import a local directory or files into it. -2. Ingestion returns a durable job ID. A UI can show queue state, processing stage, failure, completion, and the currently - available version; percentage progress is not required. -3. Markdown and independently imported text images use Markdown parsing and RapidOCR respectively, followed by shared - chunking, full-text/vector indexing, and document publication. -4. Changed originals or explicit reprocessing retain the document ID and publish a new revision on success. Failure keeps - the previous version available. -5. Manual chunk edits and removals also create document revisions and preserve history. Retrieval can select multiple - knowledge bases in the same Scope. -6. Deletion changes logical visibility while retaining business content, snapshots, and history. Ordinary, exact, historical, - evidence, and retrieval paths all enforce deletion. - -The first phase covers SQLite, SeekDB, and OceanBase; local OpenDAL fs; Markdown; RapidOCR with ONNX Runtime; rule-based -chunking; and manual editing. Embedded Markdown images retain their references without automatic fetching or OCR. A -large-corpus benchmark is not required. PDF/Office, scene-image understanding, remote uploads/original storage, periodic -directory synchronization, semantic/LLM chunking, restoration/permanent erasure, per-knowledge-base embedding spaces, and -uninterrupted index switching are outside this phase. Job status APIs are included; a complete management UI can build on -the same contract, and a scheduling mockup is not evidence of implementation. +1. An administrator creates a knowledge-base Scope and saves parsing/chunking configuration, then imports local files or a + directory accessible to the Server. +2. The plugin saves immutable snapshots, registers Sources, and submits processing-request Sources. Acceptance is not parsing success. +3. Framework generate asynchronously processes Markdown/images, prepares complete chunks and indexes, then publishes a document. +4. Changed content and explicit reprocessing retain the document ID. Failures preserve existing revisions. Status distinguishes + pending, latest failure, published, and conflict/skipped. +5. Synchronous chunk edits/removals increment the document revision; core records a lineage_only success Source in the same transaction. +6. Whole-document soft deletion uses generic forget: deprecated, excluded from normal retrieval, with no new revision. Bodies, + originals, and history remain stored. + +The first phase does not promise in-flight cancellation, Source deletion, knowledge-base cascades, physical erasure, an +independent queue, online model switching, cross-base aggregate retrieval, continuous directory sync, or remote runners. +PDF/Office, scene-image understanding, OCR of embedded Markdown images, semantic/LLM chunking, and large-corpus benchmarks +are out of scope. Restore/merge methods are not implemented initially; generic routes report unsupported. Import is not restoration. # Reference-level explanation -## 1. One business plugin and naming +## 1. Plugin, Scope, and framework dependencies -The plugin registers dedicated document Source types, the `knowledge-base` and `document` families, background task entry -points, its storage migrations, and APIs. Ingestion, parsing, chunking, and retrieval are internal modules, not separately -installed plugins. The design assumes that [#2549](https://github.com/oceanbase/powercontext/pull/2549) and -[#2579](https://github.com/oceanbase/powercontext/pull/2579) will provide the required composite registration, constrained -writes, and API extensions; their proposed contracts are not treated as released interfaces. +Follow [#2549](https://github.com/oceanbase/powercontext/pull/2549) for single-family plugins, Source definitions, writers, +models, and storage, and [#2579](https://github.com/oceanbase/powercontext/pull/2579) for routes, Scope management, and upgrades. +[#2616](https://github.com/oceanbase/powercontext/pull/2616) is an implementation dependency; capabilities such as dedicated +storage on all three backends require actual implementation and validation. [#2617](https://github.com/oceanbase/powercontext/pull/2617) +is a future collection integration, not a prerequisite for explicit local imports. -| Location | Identifier | +| Object | Model | | --- | --- | -| Display name | Knowledge Base | -| Plugin and knowledge-base family | knowledge-base | -| Whole-document family | document | -| Ownership / multi-base selection fields | knowledge_base_id / knowledge_base_ids | -| Module and configuration prefix | knowledge_base | -| Plugin table prefix | pc_knowledge_base_ | +| Knowledge base | Ordinary Scope; scope_id is its identity | +| Plugin | knowledge-base, one installed directory, one document family | +| Original | knowledge-base-file Source, pinned snapshot and original path | +| Processing request | knowledge-base-process Source, pinned original reference, configuration, base, and request identity | +| Document | document Artifact, bounded whole-document manifest | +| Chunk | Immutable result in plugin storage, not a separate Artifact | ```mermaid flowchart TD - S[Scope] --> K1[knowledge-base K1] - S --> K2[knowledge-base K2] - K1 --> R[Resource: stable file identity] - R --> O[Immutable original Source] - R --> J[Independent job] - O --> P[Parsing and rule-based chunking] - J --> P - P --> C[Immutable chunk result and indexes] - C --> D[document revision: bounded manifest] - E[lineage_only operation evidence] --> D - D --> Q[Knowledge-base retrieval and exact chunk reads] + S[Scope: knowledge base] --> C[Plugin configuration] + S --> O[Original Source and immutable snapshot] + O --> R[Processing request Source] + R --> G[Framework generate and cursor] + G --> I[Immutable chunks and indexes] + I --> D[document Artifact revision] + U[Synchronous chunk edit] --> D + D --> Q[Retrieval and exact chunk reads] ``` -Scope remains the authorization boundary. A knowledge-base Scope contains document Sources, documents, and knowledge bases; -operation evidence is internal. Ownership is explicit and validated rather than inferred from tags or lineage. Only the -document pipeline may consume original document Sources; originals are not lineage_only. Framework admission must cover -write notifications, startup reconciliation, automatic consumers, and manual generation. A Source type name or suppressed -notification is not isolation. Shared-database deployment relies on those generic extensions and does not require a separate -PC Server by default; isolation cannot be claimed before admission is implemented. - -The plugin owns its embedding/index profile. Installation may initialize compatible defaults from the main configuration, -without following subsequent changes. Credentials remain deployment configuration. Initially, documents in a Scope share -the plugin profile; parsing/chunking may vary by knowledge base. Jobs and result metadata pin the relevant profiles. -Active profile references live in knowledge-base Artifact configuration and must agree across active knowledge bases in a -Scope; new bases inherit that reference. Environment settings are initial defaults, not overrides for existing data. Model -changes require switch_model_and_rebuild for the entire shared Scope, as specified in 8.1. +Create through ctx.scopes.create with the existing server.admin requirement; the same idempotency key returns the same Scope. +The framework's plugin external reference identifies creator ownership. Scope fields hold title/summary; plugin tables hold +business configuration. Retry configuration after a successful Scope creation if its separate write fails; reject imports +until configuration is ready. Reuse Scope read/contribute, Artifact write, and framework preconditions. Plugin routes must not +treat Scope contribution as permission to modify every document. -## 2. OpenDAL, identity, and deduplication +Plugin inputs subscribe only to processing requests, so originals do not independently trigger this plugin again. Deployment +reserves knowledge-base Scopes for this use and does not enable other content consumers. A Source type name is not framework +enforced exclusive admission; isolation from arbitrary other consumers is not a guarantee of this plugin. -The first phase accepts only directories accessible to the plugin runtime. Importer, Server, and Worker use the same storage -alias to access a managed immutable snapshot directory, including local container volume mappings. OpenDAL fs does not make -a remote client's path accessible. Enforce root containment and a fixed symbolic-link policy. +## 2. Local storage, identity, and request acceptance -A Source records `original_path` for provenance and `snapshot_ref` with store_id, object_key, and digest for reading. Save the -snapshot and calculate SHA256 from its actual bytes before durable job acceptance. Parse the snapshot, not a mutable original. -mtime/size are hints, not content identity. +OpenDAL fs manages snapshot directories accessible to the importer, Server, and Workers. Original paths are provenance; +parsing reads snapshots only. Enforce root containment and a fixed symlink policy. Save bytes and compute SHA256 before +Source registration; mtime/size cannot replace the content hash. ```text -file_key = (scope_id, knowledge_base_id, collection_id, normalized_relative_path) -document_id = stable_hash(identity_version, file_key) -source_key = stable_hash(source_schema_version, file_key, raw_content_digest) -processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) -index_key = hash(complete embedding inputs, plugin profile and projection versions) +file_key = (scope_id, collection_id, normalized_relative_path) +document_id = stable_hash(identity_version, file_key) +source_key = stable_hash(source_schema_version, file_key, raw_content_digest) +request_key = (scope_id, idempotency_key) +result_id = digest(canonical complete chunk result and provenance) ``` -Collection identity comes from the storage instance and normalized root, independent of scan/job IDs. Compare complete -identities on hash matches and never truncate paths. A Source payload pins ownership, document ID, file identity, media type, -digest, and snapshot. Replay preserves canonical capture metadata, including the original capture time. - -| Case | Behavior | -| --- | --- | -| Same request key and parameters | Return the same job/determined result; different parameters under that key conflict | -| Same file bytes/profile with an available result | Reuse Source/document, verify index availability, skip parsing | -| Different request key matching an active target | Return 409 with the existing job reference; do not duplicate execution | -| Changed original bytes | New Source, same document ID, new target generation and job | -| Explicit reprocessing / changed chunking profile | Reuse Source and document ID; publish a new revision on success | -| Only embedding/index configuration changes | Rebuild from committed chunks without repeating OCR | -| Same bytes at a different path / knowledge base | Separate logical Sources/documents; physical snapshots may be shared | -| Manual edits exist | Ordinary duplicate import preserves them; reprocessing requires manual_edits_policy=discard | - -An existing Source does not prove processing succeeded. Reverting file bytes may reuse an older Source; the resource's latest -target, not journal order, defines desired input. Renaming initially means a new file; disappearance does not automatically -delete it. Reimport never silently restores a deleted identity. Explicit reprocess is not skipped as ordinary import merely -because its output might be identical. - -## 3. Lightweight parsing and chunking - -A parser accepts a snapshot reference and pinned configuration, returning Markdown, source locators, and optional warnings. -An internal format registry selects Markdown or image parsing. Future formats add a parser and fixtures without requiring a -universal document AST, capability negotiation, or a separate parser plugin system. Parsers do not write Artifacts, job state, -or indexes. An external adapter may return a pending reference that the execution layer persists and resumes. - -Markdown uses markdown-it-py for structure and source mapping. Images use RapidOCR with ONNX Runtime, retaining boxes, order, -confidence, and preprocessing coordinate transforms. Normalization produces Markdown without inventing complex headings, -tables, or diagram semantics. Map normalized spans back to the image and declare locator precision. Derived Markdown never -replaces the original Source. - -- Group by headings/content blocks, recursively splitting oversized blocks. Without reliable headings, recursively split - paragraphs and sentences. -- Preserve code, tables, and list steps where possible. Split oversized tables by rows with headers and oversized code with - language/continuation metadata; hard limits still apply. -- Apply overlap to split long passages rather than mechanically across sections. Include Chinese punctuation boundaries. -- Preserve heading paths and original locators. Validate the complete embedding input, including heading prefixes, against - the model token budget; character counts are not token counts and silent truncation is forbidden. -- Parameters include max_chunk_chars and overlap_chars; 1200/100 are examples to validate, not quality claims. -- Validate UTF-8, image decoding/pixel limits, model versions, and resource limits. No-text OCR is an explicit failure, not a - successful empty document. - -Rules remain deterministic and testable. Changed chunking configuration may reuse validated parsing output; a complex stage -cache is not required initially. - -## 4. Persistence and relationships - -### 4.1 Reuse existing schemas unchanged - -| Table | Responsibility | -| --- | --- | -| pc_sources | Immutable original references and lineage_only evidence for successful user/deletion operations; no new columns | -| pc_artifacts | Knowledge-base configuration, document manifests, immutable revisions | -| pc_artifact_heads | Current revision, lifecycle_state, governance_generation | -| pc_scopes | Reuse the existing Scope row for short core transaction serialization; no schema change or task counter in version | -| pc_artifact_lineage_sources / pc_artifact_lineage_artifacts | Exact-revision input/operation evidence and base references | -| Existing permissions, tags, and references | Shared semantics, without unbounded jobs or member JSON | - -Existing processing intent, cursor, lease, and binding-state tables are not used by this queue and receive no knowledge-base -fields or records. Source journals may remain part of existing storage constraints but never drive job discovery/completion. +Collection derives from the storage alias and normalized root, not a scan batch. Compare full identities on hash matches. +The same file in different Scopes is independent. Same path/bytes reuse the original Source; changed bytes create a new Source +but retain the document ID. Renames are new files; disappearance does not automatically forget a document. -### 4.2 Three plugin domain tables +Each processing request pins original_source_ref, snapshot_ref, processing settings, independent model fingerprint, +base_revision, manual_edits_policy, and request digest. Existing documents pin the accepted revision; first publication has an +explicit no-head precondition. Ordinary duplicate imports reuse available matching content/configuration. Explicit reprocessing +and user retries use new request keys, producing new request Sources even for unchanged originals. Ordinary imports preserve +manual edits; discarding them requires explicit discard authorization. -Tables belong to plugin-owned storage and migrations, reusing SQLite/SeekDB/OceanBase connection and adapter capabilities. -Full-text/vector auxiliary structures are not included in the domain-table count. - -| Table | Key fields and constraints | -| --- | --- | -| pc_knowledge_base_resources | scope_id, knowledge_base_id, resource_kind, resource_key, document_id, source_ref, identity_payload, lifecycle_state, deleted_at, target_generation, current_job_id | -| pc_knowledge_base_jobs | job_id, scope_id, knowledge_base_id, document_id, operation, idempotency_key, request_digest, input_snapshot, target_generation, base_revision, state, stage, attempt, next_run_at, execution_token, lease_owner, lease_expires_at, error_code/summary, external_task_ref, result_id, result_revision, result_kind, parent_job_id, checkpoint, cleanup_cursor | -| pc_knowledge_base_chunks | scope_id, knowledge_base_id, document_id, result_id, chunk_id, ordinal, text, text_length, content_digest, heading_path, source_locator, origin, edit_metadata | +First persist bounded immutable acceptance parameters in a plugin resource row, then idempotently register the original and +request Sources, and finally record their actual SourceRefs. Framework generate can start before the plugin acknowledgement +fields are saved: execution uses the committed request Source and pinned acceptance parameters, not another ready flag. +Return accepted only after the request Source is durably confirmed. After a lost response, replay the same key/parameters to +complete registration; a key reused with different parameters conflicts. This register is not a queue: requests without a +successfully registered Source have no background-execution promise and callers can retry. Unreferenced snapshots are not searchable. -Resources has exactly two record kinds, not an open-ended object platform: +Directory ingestion uses bounded file batches through this same acceptance path and returns per-item receipts. Enumeration +completion does not mean parsing completion. No independent directory-scan job is persisted initially; clients submit large +directories in batches, and repeated enumeration deduplicates by file identities and request keys. -- `document`: one row per stable logical file, created before the first parse; path identity, current target, and deletion - marker, without precreating an empty document Artifact. -- `source`: one row per original Source with ownership and its independent deletion marker; no growing JSON array of versions. - Successful operation evidence inherits visibility from its target Artifact. - -The primary key is `(scope_id, knowledge_base_id, resource_kind, resource_key)`. Document keys derive from file_key; Source -keys include a hash of the complete SourceRef identity. Preserve/compare complete identities and prohibit cross-base Source -ownership. SourceRef includes both source_type and source_id. Only document rows use target generation/current job fields. -Deletion markers are one-way. The published revision comes only from the Artifact head, without a second publication pointer. -Implementation fixes common timestamps and bounded error/JSON storage types. - -Jobs has a unique constraint on `(scope_id, knowledge_base_id, operation, idempotency_key)`. Its request digest covers all -business parameters and preconditions. Index due jobs, expired leases, document references, and knowledge-base ownership. -The target row serializes requests per document rather than relying on backend-specific partial unique indexes. Terminal jobs -retain idempotent receipts; bounded errors and attempt counters avoid separate receipt/attempt tables. - -Chunks uses primary key `(scope_id, knowledge_base_id, document_id, result_id, chunk_id)` and unique ordinal within a result. -`result_id` identifies immutable output before core allocates the actual revision; never guess the next revision when writing. -Each complete result has its own chunk snapshot; vectors are derived indexes. `text_length` counts Unicode code points. - -The bounded document manifest contains title, knowledge_base_id, file identity, root SourceRef, result_id, chunk count/digest, -processing/index fingerprints, manual-edit marker, applied_job_id, and necessary operation summaries. It contains neither -body text nor an unbounded chunk ID list. Exact revisions resolve results through their manifests, independently of current -search indexes. - -## 5. Independent queue and state machine - -```mermaid -stateDiagram-v2 - [*] --> queued - queued --> running - running --> succeeded - running --> retry_wait - retry_wait --> running - running --> waiting_external - waiting_external --> queued - running --> failed - queued --> cancelled - running --> cancelled - waiting_external --> cancelled - retry_wait --> cancelled - queued --> superseded - running --> superseded - waiting_external --> superseded - retry_wait --> superseded -``` +## 3. Parsing, chunking, and original provenance -`stage` is independent of state: ingest, parse, chunk, index, publish, cleanup. External waits persist a remote reference and -next_run_at, then release the Worker. A later poll resumes work without holding a process or transaction. Remote submissions -use stable idempotency keys; services without idempotency need reconciliation, not a promise of exactly-once external calls. +Markdown uses markdown-it-py for headings, blocks, and source mappings. Standalone images use RapidOCR with ONNX Runtime, +retaining boxes, order, confidence, and coordinate transforms; normalized Markdown enters the same chunker. Do not infer +complex tables or flowcharts. Embedded Markdown images remain references. -KnowledgeBaseTaskSupervisor scans only plugin jobs and owns claim, heartbeat, expiry recovery, and completion. Reuse separable -process-launch/termination, budget, and shutdown tools. Do not attach to existing Scope/binding discovery, intents, or Source -cursors. If the existing Supervisor is coupled to those mechanisms, implement a lightweight plugin scheduler rather than -putting per-file jobs into its tables. Publication is serial per document, with bounded concurrency across documents. +Split by heading/content blocks, recursively splitting oversized blocks at paragraphs/sentences. Preserve code, tables, and +SOP steps where possible; split oversized tables with repeated headers. Overlap applies to split long paragraphs. Configure +max_chunk_chars/overlap_chars; 1200/100 is an initial test value. Validate the complete embedding input, including heading text, +against model token limits without silent truncation. Report invalid UTF-8, image dimensions/decoding, and OCR with no text. -`target_generation` identifies the desired result; `execution_token` identifies the currently authorized attempt. Claims, -heartbeats, and updates check the token. New targets supersede old targets; lease recovery rotates the token. SQLite uses its -actual transaction/CAS capabilities rather than assuming every backend supports SKIP LOCKED. +Parsers return Markdown, locators, and warnings, not cursor or Artifact changes. New formats use an internal parser registry, +not additional plugin types. -For ordinary requests, authorization/lifecycle checks precede replay recognition, which precedes current-base checks for new -requests. A successful network retry must not fail solely because its original ETag is stale. The deletion entry point allows -authorized inspection of bounded deleted-target state to finish cleanup instead of rejecting it with generic 410 first. -Terminal jobs never revive. Automatic bounded retries remain within a job; ordinary user retries use a new key/job. Repeated -deletion automatically creates successor cleanup jobs as specified in section 7. Cancellation cannot undo publication or any -committed deletion tombstone/retirement; cancelled edges in the state machine are conditional on this cutoff. -Edits/removals pin their base and reject conflicting active changes rather than silently queue or rebase. A failed file does -not block the whole Scope. +A request records the original SourceRef and snapshot. Generate directly references only request Sources in its current window; +a previously consumed original may be outside that window and cannot bypass writer restrictions. The document manifest retains +original provenance, providing a verifiable document → request Source → original Source chain without claiming that the original +is always direct lineage. Synchronous edits preserve current lineage and original locators and add core's success Source. -## 6. Acceptance, publication, and cross-store recovery +## 4. Plugin storage and models -Core and plugin storage do not share a transaction. Source, job, chunks, indexes, and Artifact cannot be described as one atomic -commit. +ctx.storage uses the Server backend: a dedicated SQLite file or a dedicated SeekDB/OceanBase database, precreated by the deployer +when database-creation permission is unavailable. The plugin selects migrations and full-text/vector implementations by backend, +without changing existing core schemas. Originals stay in local OpenDAL directories rather than SQL body columns. -| Boundary | Behavior and recovery | -| --- | --- | -| Snapshot | Save immutable original bytes; unaccepted orphan snapshots are invisible, with permanent cleanup specified separately | -| Plugin acceptance transaction | Validate/lock the resource target, check idempotency, persist fixed inputs and job; recoverable after 202 | -| Source registration | Worker idempotently saves/reuses the Source in the ingest stage; retry if Source succeeded but job acknowledgement did not | -| Computation outside transactions | Parse/OCR/chunk/embed pinned snapshots and settings without database locks | -| Plugin result preparation | Store complete immutable chunks and usable indexes under result_id; verify count/digest; unreferenced output is invisible | -| Short core publication transaction | Check base, ownership, and execution eligibility; write document revision, required operation evidence Source, lineage, and head | -| Plugin completion transaction | Record actual result_revision and succeeded; reconcile applied_job_id/result_id after lost acknowledgement rather than republish | - -Core provides the commit gate using the existing `pc_scopes` row. OceanBase/SeekDB use a row lock in the same core transaction; -SQLite uses a core-database `BEGIN IMMEDIATE` write transaction. No lock table or Scope field is added. Publication, deletion, -new-target acceptance, cancellation, execution-token claim/replacement, lease recovery, and model-switch control all acquire -this gate before plugin resource/job locks and then Artifact heads. Ordinary heartbeats only renew the matching token without -transferring ownership. Ingestion and synchronous Artifact mutation entry points must obey the gate too. - -After obtaining both sides' locks, reread target, token, lease, Source markers, parent lifecycle, and already-published core -results. Publication uses the very same core connection/transaction holding the Scope lock, never another unlocked connection. -Cancellation/target replacement/reclaim reconcile inside the gate, commit plugin state, then release the core lock. Publication -commits core first and records plugin success afterward; missing acknowledgement is reconciled. These are separate commits, -not a cross-store atomic transaction. - -Losing the plugin database connection does not release the core lock, so another executor cannot cancel or reclaim meanwhile. -Losing the core connection prevents that transaction from publishing. Any connection error or uncertain commit outcome ends -the attempt; automatic reconnect must not reuse old eligibility. Recovery obtains a fresh core gate before reconciliation and -plugin-state validation. Every control path follows core-before-plugin lock order; never wait for core while holding plugin locks. - -Only short commits within a Scope are serialized. Parsing, OCR, embedding, index construction, and directory enumeration run -concurrently outside the gate; no model calls, DDL, or long computation occurs inside it. Verify actual backend locks, -connection failures, and timeouts rather than substituting memory locks or a one-time token check. Prepared output is immutable; -different recomputation uses a new result_id. Ordinary publication failures retain the old head and usable old index. - -## 7. Operation evidence, editing, and soft deletion - -Successful Artifact creation, modification, and deletion require a system `lineage_only` Source associated with the actual -output revision. Queued requests are not evidence of successful mutation. Reuse existing create/replace evidence semantics; -a bounded operation summary records specific delete/remove actions and reasons without assuming a new core operation enum. -Jobs record intent/execution; operation Sources record success, linked through job/operation IDs. - -| Operation | Version and visibility | +| Plugin domain table | Fields and constraints | | --- | --- | -| Create/configure knowledge-base | Create or add a configuration revision with operation evidence | -| Parse/reprocess document | Publish a revision under the same document ID with original lineage; retain evidence for user-triggered changes | -| Edit/remove chunk | Increment document revision, produce a complete result, link successful operation evidence, retain previous rows | -| Delete document/knowledge-base | Create a deletion revision with a bounded deletion summary and retire the head in the same core transaction; link deletion evidence | -| Delete original Source | Mark the source resource and immediately deny original/derived reads; finish document retirement, deletion evidence, and index cleanup asynchronously | - -Deletion revisions are a plugin convention, not a change to other families' governance. A deletion revision may reuse the -previous result_id without copying chunk bodies. Its operation summary must actually create a revision rather than be skipped -by an identical-content put no-op. Evidence, lineage, revision, and head commit together in core; failure creates no success -evidence, and replaying the same accepted operation does not add revisions. - -Deletion must distinguish a published document from a logical file that has never published an Artifact. Under the existing -core Scope gate and plugin resource/job locks, reread the head and reconcile publication before selecting the branch. If a head -exists, use the revision/retirement protocol above. If the file has never published, deleting it marks its document resource -and invalidates pending publication; no Artifact ETag, empty Artifact, deletion revision, or Artifact-success evidence is required. -Knowledge-base cascades include these unpublished resources. Source deletion marks the selected Source and invalidates only -work depending on it; it does not retire a nonexistent document or delete unrelated Source versions. Direct document deletion -still leaves original Sources readable. Missing heads for previously published files are consistency errors, not this branch. -The resource tombstone and invalidation commit before releasing the gate, so a concurrent first publication cannot slip through. -The job records completion; repeated deletion succeeds without inventing an Artifact operation. A committed resource tombstone -is a deletion effect and prevents cancellation, even when no Artifact exists. - -Manual text replacement may retain a logical chunk ID, but references include a revision. Rechunking may create new IDs. -Edited text is marked non-verbatim with original locators and edit provenance. Removing the last chunk permits a zero-chunk -result with no current retrieval hits. Duplicate import cannot overwrite manual edits; explicit reprocessing requires discard. - -Knowledge-base deletion first commits its deletion revision/retirement, immediately hiding all children. An accepted cleanup -job survives restart, marks Sources, deletes documents, and cancels processing in batches. Each changed Artifact gets its own -evidence, sharing an operation ID for the cascade. Cleanup is allowed under a deleted parent and is not cancelled by ordinary -processing parent checks. Its cursor is plugin batch progress only. Persist the deletion/cleanup job before the first deletion -effect. Once a resource tombstone or Artifact retirement commits, deletion is non-cancellable: failures require completion or -recovery rather than reporting cancellation with unfinished side effects. Queued deletion without effects remains cancellable. - -Deleting a document leaves its original Source readable. Deleting an unpublished replacement Source preserves an old result -based on another original. If S1 supplied an old revision and S2 supplied a complete reparse, deleting S1 preserves the current -version based only on S2 but blocks history that depends on S1. A Source deletion response acknowledging an effective deletion, -including 202 cleanup pending, requires a committed tombstone; job acceptance alone is not deletion. That tombstone is the visibility cutoff for -that original and its derived content. Reads/retrieval starting afterward must check it even when the document head is still -active or index entries remain. Content already returned before deletion is not recalled. Only document retirement, -deletion revision/evidence, and index maintenance may be eventually consistent; content must not remain readable while cleanup -is pending. Fail closed when visibility checks are unavailable. Resource markers and retirement may finish in stages, with -reads checking applicable parent, document, exact root, and Source markers. Generic Source, -exact/historical Artifact, and evidence reads require framework visibility extension points; plugin search filtering alone -does not satisfy deletion. Missing ownership registration fails closed rather than returning unguarded content. -Controlled internal recovery may inspect retired history for reconciliation; an authorized management route may expose bounded -cleanup status after deletion without exposing bodies or a public bypass parameter. - -Repeated deletion uses the same deletion entry point/operation, without a repair/retry API. After authorization, inspect the -original deletion and cleanup state even for a deleted target. A deletion marker or the original stale ETag does not prevent -cleanup; still-active targets retain ordinary preconditions. Conflicting parameters under an idempotency key still return 409. - -The cleanup rules below apply after deletion effects exist. If the initial deletion failed or was cancelled before taking effect, -a repeated deletion accepts a new deletion job under ordinary preconditions; the same idempotency key still replays its original receipt. - -| State when deletion is repeated | Result and action | +| pc_knowledge_base_resources | Primary key (scope_id, resource_kind, resource_key); fixed scope/document/request kinds; bounded payload, request_digest, source_ref, document_id, latest processing observations and timestamps | +| pc_knowledge_base_chunks | Primary key (scope_id, document_id, result_id, chunk_id); ordinal unique within a result; text, text_length, content_digest, heading_path, source_locator, origin, edit_metadata | + +Resources is a fixed-purpose register, not a generic task framework: scope rows hold configuration/version, document rows stable +file identities, and request rows immutable accepted inputs, receipts, and latest attempt observations. No leases, execution +tokens, claiming queue, or cleanup cursors; do not copy the Artifact publication pointer or lifecycle. Request results may refer +to exact revisions for reconciliation, but core determines success. Full-text/vector auxiliary structures are derived indexes, +not additional domain tables. + +Document content holds only title, original SourceRef, file identity, result_id, chunk count/digest, configuration fingerprints, +manual-edit markers, and applied_request_ref. Neither bodies nor unbounded chunk-ID lists belong in the manifest. Result IDs +derive from canonical complete results, never from a predicted uncommitted revision number. + +The plugin independently configures and creates model clients. Deployment supplies credentials; Sources/Artifacts do not store +them. Do not automatically follow ctx.models or Server model changes. Initially one fixed embedding profile serves the plugin, +including model identity/version, dimensions, complete input rules, and normalization version. Equal dimensions do not establish +model compatibility. If existing indexes disagree with deployment configuration, reject vector queries and new publication and +require controlled migration; do not silently replace configuration or mix spaces. Online model switching is not included. +Same-profile index repair reads committed chunks. Parsing/chunking configuration may vary by Scope and is pinned in each request. + +## 5. Framework consumption, status, and failure handling + +Declare on_sources and processing-request inputs; reuse framework generate/Supervisor, Scope bindings, consumption cursors, +lease fencing, and failure backoff. No independent jobs table or plugin Worker scheduler. Each invocation opens at most one +writer.transaction; core atomically commits Artifacts, the cursor, and invocation acknowledgement. Use a small max_sources and +bounded file sizes to keep OCR/model windows within limits; arbitrary files are not guaranteed to fit framework timeouts. + +| Event | Behavior | | --- | --- | -| Initial deletion or cleanup job remains active | Return the same deletion-operation identity and current job, 202; no duplicate | -| Cleanup incomplete and previous job failed/terminated | Create a new background cleanup job with parent_job_id referring to the original deletion job, 202; never revive the old job | -| Cleanup complete | Return 200 already_deleted; no new job, revision, or evidence | - -Serialize this check and successor creation under the core Scope gate so concurrent repeated deletes cannot create multiple -active cleanup jobs. The internal job uses a fresh derived idempotency key while the client's deletion identity/input remains -unchanged. Responses may refresh cleanup_job_id/status while referring to the same deletion operation. Reconcile tombstones, -Artifact deletion summaries, and the original operation ID; skip completed objects and generate revisions/evidence only for -Artifacts not yet changed. This applies to Sources, documents, and knowledge bases. A deleted parent permits authorized cleanup, -not ordinary writes or content reads. - -## 8. APIs and retrieval - -Reuse Source encoding/identity/validation; Artifact CRUD/history/tags; authentication; permissions; ETags; pagination; -references; and error envelopes. File ingestion uses the plugin's Source acceptance capability, not a write path that triggers -old consumers. Expensive edits return 202 through job APIs rather than silently changing synchronous Artifact PUT into an -asynchronous success. Generic writes must not bypass job, version, evidence, or deletion rules. - -Routes are proposed contracts. Plugin APIs follow #2579; registration syntax follows the framework implementation: -`P=/v1/plugins/knowledge-base/api/scopes/{s}`, `D=/v1/scopes/{s}/artifacts/document/{d}`. - -| Operation | API / result | +| Request submitted without a result | Report pending, without invented percentages | +| Deterministic input error such as invalid format or no OCR text | Persist a bounded failure observation and skip that input; normal window acknowledgement permits subsequent requests | +| Database, model service, or durable index failure | Raise; core rolls back and the cursor does not advance; framework retries with backoff | +| Pinned base changed or document no longer active | Record conflict/skipped, never automatically replace the base; caller submits a new request | +| Core publication completed | Derive published state and exact revision from manifest/history applied_request_ref | +| Core succeeded but plugin status acknowledgement failed | Reconcile core, not failure or duplicate publication inferred from a missing status | + +Failure observations describe the latest attempt, not proof of cursor acknowledgement. Plugin status cannot advance consumption +or justify skipping unproven core writes. Persistent infrastructure failure may block subsequent windows in the Scope; independent +unlimited per-file concurrency and a dead-letter queue are not promised. User retries of deterministic failures use new requests; +old Sources remain unchanged. Processing requests express intent, not lineage_only success. + +Require no head for first publication. Updates validate the pinned base, original, manual-edit policy, and lifecycle. Framework +retries cannot rewrite the request's base or discard policy. If an edit/forget occurs after preparation, publication uses framework +revision/governance concurrency checks and must not reactivate deprecated documents. An implementation unable to protect lifecycle +under races must fix and test its framework adapter; an in-memory plugin lock is not a substitute or evidence of support. + +## 6. Publication and index consistency + +1. Parse and calculate vectors outside the core transaction; durably store immutable chunks and their full-text/vector indexes, + validating counts, digests, and readability. +2. Validate preconditions and put a manifest referencing result_id and index fingerprints in writer.transaction. Generate commits + its cursor with the revision; user edits commit success evidence with the revision. +3. A failed core commit leaves prepared results invisible and the previous manifest/index usable. Retries do not overwrite old results. +4. Retrieval candidates must match the active current document's result_id/profile. Refill after filtering; unpublished results + must not consume the effective top-k. + +Isolate indexes by result rather than overwriting current candidates under document_id alone. Model/file computation stays outside +short transactions. No additional core Scope-row gate or distributed transaction protocol is introduced. Exact historical chunks +resolve through their revision's manifest, independently of current search indexes. Unreferenced prepared data does not change +visible results; permanent cleanup is a separate contract. + +## 7. Synchronous chunk editing and soft deletion + +Generic Artifact PUT invokes update_artifact synchronously for chunk edits/removals; these are not plugin-route writes or queued +commands. The plugin editing payload is a bounded chunk-change description containing a chunk ID/new text or removal action. +The service reads the base revision and composes the complete result. Only the service creates manifests; reject caller-supplied +arbitrary result IDs or original ownership. Core permits plugin normalization of submitted content; arbitrary manifest replacement +is not exposed. + +Require If-Match, prepare the new result/indexes, then perform exactly one put(expected_revision=...). Core stores the submitted +edit payload as a lineage_only Content Source in the same transaction and increments the document revision. Edits retain logical +chunk identity and original locators, marking non-verbatim manual text. Removing the final chunk permits a zero-chunk revision. +Edit evidence can contain the new text; existing permissions apply, and forget does not erase that evidence. + +Model calls obey synchronous time and edit-size limits; failures publish no partial result. After an uncertain response, read +current revision/lineage before retrying. An old If-Match cannot be reused blindly. Generic PUT does not add an idempotency-key +or exactly-once HTTP guarantee. + +Whole-document soft deletion uses generic forget, invoking forget_artifact with exactly one set_lifecycle(deprecated). This is +only a lifecycle transition: no new content revision, no plugin-specific deletion evidence, and no physical removal of bodies, +indexes, or snapshots. Normal retrieval and Prepared Context exclude deprecated documents. Generic get/history/evidence retain +framework visibility; authorized exact chunk reads and rendering can show retained versions. Do not promise all content becomes +unreadable. Core owns lifecycle; no duplicate document tombstone in plugin storage. Index cleanup is not a prerequisite for forget. + +Reimport, reprocessing, and late work never automatically restore forgotten documents; synchronous edits require active documents. +Before a document exists there is no forget target. In-flight import cancellation is not supported; do not create empty Artifacts +or deletion revisions. No Source deletion or knowledge-base cascade API; physical Scope deletion is not soft deletion. Repeated +forget follows framework preconditions/no-op behavior without scheduling cleanup work. + +## 8. APIs, retrieval, and authorization + +Let `P=/v1/plugins/knowledge-base/api` and `D=/v1/scopes/{s}/artifacts/document/{d}`. Declare plugin routes through PluginApi/Route +using supported response facilities. Accepted below is a business state, not an assumption that custom HTTP 202 is available; +default successful JSON responses may use 200. + +| Operation | API and response | | --- | --- | -| Create knowledge base | POST `/v1/scopes/{s}/artifacts`, family=knowledge-base | -| Knowledge-base/document overview and history | Generic Artifact GET/revisions, bounded manifest | -| Import local files/directory | POST `P/imports`, explicit knowledge_base_id, root/paths, idempotency_key; 202 job receipt | -| Reprocess/edit/delete | POST `P/jobs`, typed operation, pinned target and preconditions; repeating delete_source/delete_document/delete_knowledge_base repairs cleanup automatically; cleanup is internal-only | -| Change model and rebuild index | POST `P/jobs`, operation=switch_model_and_rebuild, explicit confirmation of Scope-wide impact; existing job status APIs | -| Job list/detail | GET `P/jobs`, GET `P/jobs/{job_id}`, pagination, stage, state, bounded error, successful revision | -| Cancel | POST `P/jobs/{job_id}/cancel`, nonterminal work without publication or committed deletion effects; model switching is also non-cancellable after publication starts | -| Chunk directory | GET `P/documents/{d}/revisions/{rev}/chunks`, paged metadata without body | -| Single chunk | Append `/{chunk_id}`, body, provenance, edit metadata | -| Batch chunks | Append `/batch-get`, POST bounded chunk_ids | -| Hybrid retrieval | POST `P/retrieve`, knowledge_base_ids, query, mode, limit; chunk hits | - -Plugin chunk routes retain Artifact document IDs/revisions. Their paths are separate from generic Artifact routes while -preserving exact-revision semantics: resolve result_id through that revision's manifest, never fall back to the current head. -Directory cursors bind Scope/document/revision and order by ordinal. Batch-get requires nonempty, unique IDs and preserves -request order. Authorize the parent first; any missing ID fails the whole batch with 404. Bound ID count and response bytes; -reject over-limit requests without truncating bodies. Authorized deleted reads return 410; zero-chunk directories are empty. - -Create a knowledge base: +| Create knowledge base | POST `P/knowledge-bases`, ctx.scopes.create plus configuration; returns scope_id | +| Import files | POST `P/scopes/{s}/imports`, bounded paths and idempotency_key; per-file request SourceRefs | +| Reprocess/retry | POST `P/scopes/{s}/documents/{d}/reprocess`, base, pinned configuration, original reference, new request key | +| Processing status | GET `P/scopes/{s}/imports/{request_id}`, acceptance, latest attempt, and verifiable publication | +| Document overview/history | Generic Artifact GET/revisions, bounded manifest | +| Edit/remove chunk | PUT `D`, If-Match, synchronous new document revision | +| Soft-delete document | POST `D/forget`, revision and state_version; framework response | +| Chunk directory/body | GET `P/scopes/{s}/documents/{d}/revisions/{rev}/chunks`; append `/{chunk_id}` for body | +| Batch chunks | POST directory path plus `/batch-get`, bounded chunk_ids | +| Chunk hybrid retrieval | POST `P/scopes/{s}/retrieve`, exact revision, chunk ID, score, provenance | +| Rendering/generic search | render_artifact/search_artifacts; generic search and Prepared Context integration | + +Examples for knowledge-base creation, import, editing, forget, and retrieval: ```json -{"family":"knowledge-base","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +{"title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} ``` -Import a directory. Enumeration creates per-file jobs in bounded batches using parent_job_id. Directory completion means -enumeration/child acceptance finished, not that every file succeeded: - ```json -{"knowledge_base_id":"ops","root":"/work/docs","idempotency_key":"import-01"} +{"root":"/work/docs","paths":["restart.md"],"idempotency_key":"import-01"} ``` -Remove a chunk. Existing documents require current If-Match; first generation uses an explicit no-head precondition rather -than guessing a future revision: - ```json -{"knowledge_base_id":"ops","document_id":"doc-1","operation":"remove_chunk","idempotency_key":"edit-03","base_revision":2,"input":{"chunk_id":"chunk-3"}} +{"scope_id":"scope-ops","items":[{"document_id":"doc-1","request_ref":{"source_type":"knowledge-base-process","source_id":"request-01"},"status":"accepted"}]} ``` ```json -{"job_id":"job-03","state":"queued","document_id":"doc-1","target_generation":5} +{"content":{"operation":"edit_chunk","chunk_id":"chunk-1","text":"Check replica health before restarting."}} ``` ```json -{"job_id":"job-03","state":"succeeded","result":{"document_id":"doc-1","revision":3,"kind":"created"}} +{"content":{"operation":"remove_chunk","chunk_id":"chunk-2"}} ``` -Exact-revision directory and batch reads: - ```json -{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +{"revision":3,"state_version":0} ``` ```json -{"chunk_ids":["chunk-1","chunk-2"]} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10} ``` ```json -{"knowledge_base_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +{"hits":[{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` -```json -{"hits":[{"knowledge_base_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} -``` +Chunk APIs read the requested exact revision without current-version fallback. Directory pagination omits bodies; single/batch +reads return bounded bodies and provenance. Reject duplicate/missing IDs and excessive responses without silent truncation. +Check Scope/document permissions and ownership first; plugin storage spans Scopes, so chunk IDs alone never authorize reads. -Retrieval limit counts chunks; optional snippets are bounded and bodies use chunk APIs. Generic Artifact search still returns -Artifacts rather than chunk responses. Index candidates must match the current manifest result_id and index profile and pass -ownership, authorization, and deletion checks. Refill after filtering so invalid candidates do not consume top-k. The adapter -covers initial writes, revision replacement, rebuild, coverage/digest validation, zero chunks, deletion filtering, and locators. -Historical bodies do not require every historical search index. Same-profile rebuild retains the usable old index and cannot -publish content missing its required index. Model changes use the controlled maintenance procedure in 8.1. +Generic search retains the framework's Artifact-reference response; plugin retrieve returns chunk structures. Prepared Context +uses SearchHit text/locators within its byte budget. Normal search excludes non-active, stale, and unauthorized candidates before +refilling. Unsupported filter/rerank parameters fail explicitly. Different Scopes are authorized separately; no aggregate API +initially. Python/HTTP share business handling; MCP and Dashboard integration follows actually available framework capabilities. -Same-Scope retrieval may select multiple knowledge bases. Cross-Scope helpers authorize each explicit target, call the same -per-Scope API, fuse ranks, and preserve target identity/errors rather than compare incompatible vector-space scores. Reject -unsupported filters/rerank options. Python/MCP use the same service. Reuse Scope read/contribute and Artifact write/governance -permissions, checking every affected object. Acceptance uses 428/412 preconditions, 409 conflicts, 410 deletion, 422 validation, -413 limits, and 503 unavailability. After 202, failures are durable job states rather than conclusions inferred from logs. +## 9. Upgrade, implementation, and acceptance -### 8.1 Change model and rebuild the index +upgrade(ctx) manages plugin schema/index metadata migrations and a plugin-owned schema version. Upgrades are repeatable and +coordinate in plugin storage across instances. Keep changes compatible with overlapping code versions and retain historical +manifest/Source decoding. Initial deployments may restart for upgrades; completed hot reload is not a knowledge-base prerequisite. +Backups must include core, plugin storage, and OpenDAL snapshots; core backups do not automatically cover plugin data. -Existing data's active model, dimensions, and embedding parameters cannot be overwritten through configuration PUT, environment -refresh, or restart. Use `switch_model_and_rebuild` with a pinned target_profile identifying model/version, dimensions, complete -embedding-input rules, and index configuration; credentials remain configuration references. Because a Scope shares one profile, -the operation requires Scope administration and explicit confirmation of all its knowledge bases, not merely the initiating base. +Framework implementation must supply three-backend ctx.storage, single-family writers, synchronous modification evidence, +governance concurrency checks, Source definitions, and routes. Missing RFC features are implementation dependencies, not grounds +for additional knowledge-base lock tables, read guards, or an independent queue. Necessary adapters must preserve core contracts. -```json -{"knowledge_base_id":"ops","operation":"switch_model_and_rebuild","idempotency_key":"model-switch-01","input":{"expected_profile_id":"embedding-v1","target_profile_id":"embedding-v2","confirm_scope_wide":true}} -``` +Validate on SQLite, SeekDB, and OceanBase: -Reuse jobs' input_snapshot, checkpoint, parent_job_id, and document child jobs for old/target profiles, phase, and rebuild progress; -no control table is added. The Scope gate permits one unfinished switch operation per Scope. Durable checkpoint phases are -preparing, rebuilding, publishing, completed, aborted. Failure/process exit does not automatically clear maintenance; running job state -alone must not decide whether service is paused. Resolve maintenance from the latest effective checkpoint in the original switch -and successor chain: successor completed/aborted closes the operation while old failed records remain as history, not blockers. +- Administrator-only Scope creation, configuration retry, multi-Scope isolation, immutable snapshots. +- Retries across import acceptance boundaries, key conflicts, content deduplication, repeated handling, and deterministic failures + that do not block later files. +- Window rollback/redelivery, failure observations versus committed core success, and pinned-base conflicts without automatic rebasing. +- Markdown, real RapidOCR, oversized blocks, complete embedding-input limits, provenance, and manual-text markers. +- Synchronous edit/removal revisions and lineage_only evidence, zero chunks, model failures, and lost responses. +- Edit/forget racing generate without overwriting edits or restoring deprecated documents; retained originals/history. +- Core rollback after index preparation while old retrieval remains usable, candidate filtering, exact reads, generic search, and Prepared Context. +- Explicit model-fingerprint mismatch failures; Server model changes do not alter the plugin vector space. -| Phase | Behavior | -| --- | --- | -| Acceptance/preparing | Persist switch job and old/target profiles; pause Scope retrieval and ordinary writes/publication, retain management status and exact content reads; finish cleanup for deletions already in effect | -| rebuilding | Pin current valid document revisions, build isolated target-profile indexes from committed chunks without OCR, validate counts/digests, dimensions, and complete-input token limits | -| publishing | Publish document revisions changing only index-profile references, reusing body result_id where appropriate, with success evidence; update all active knowledge-base configuration revisions | -| completed | Verify all valid documents, knowledge-base configuration, and target indexes agree; complete under the gate and release maintenance so queries and subsequent jobs use the target profile together | - -Retrieval/ordinary writes return explicit 503 with the switch job reference during maintenance, never mixed-model results or -silent empty results. Knowledge-base creation also checks maintenance. Repeated deletion/cleanup for effects already committed -remains allowed so failed cleanup cannot deadlock preparation; new deletion requests are paused ordinary writes. -Old-profile unpublished jobs cannot commit: freeze their -eligibility and reconcile; mark unpublished old targets superseded without rewriting their inputs, and let callers submit new -requests when needed. Queries pin their profile and recheck maintenance/active profile before returning; a change yields 503 -rather than an in-flight old-model result. Exact chunk/history reads still use fixed result_id and deletion guards. Retain old indexes at least until -switch success. - -In preparing/rebuilding, cancellation/failure restores old-profile service only after verifying under the gate that no profile -revision was published and persisting aborted. Failed job state alone never releases maintenance; superseded jobs do not revive. Once publication starts, cancellation/automatic rollback is forbidden because -some objects may already use the target. Maintain the pause and complete forward recovery. Repeating switch_model_and_rebuild -with the same target and a new request key may create a successor job linked to the original switch, skipping already-published -revisions without reviving failed jobs or duplicating evidence. The same request key returns its existing job. Reject a different -target while a switch remains unfinished. Insufficient input budget in the new model fails explicitly and requires rechunking -first; never silently truncate. Neither distributed atomic commits nor uninterrupted switching are required. - -## 9. Implementation and acceptance - -Only plugin storage needs new migrations; existing core tables receive no new fields/migrations. The plugin framework must -provide registration, consumption admission, constrained publication, and visibility checks. Unchanged table schemas do not -mean zero framework adaptation. Generate bindings under the appropriate core or plugin OpenAPI ownership. - -Verify on SQLite, SeekDB, and OceanBase: - -- Multiple knowledge bases per Scope, cross-base authorization, exclusive ownership, and original-only consumption including - recovery scans and manual entry points. -- Build/run, debugging, and Wait Event Markdown from a pinned oceanbase/oceanbase commit; real text-image OCR and provenance. -- Request replay, payload conflicts, active-target conflicts, deduplication, configuration reprocessing, and edit preservation. -- Exit after acceptance, Source registration before acknowledgement, lease recovery, stale tokens, superseding, bounded retries, - and cancellation. -- Prepared output followed by core rollback; core success followed by lost task acknowledgement; old content availability, - invisible uncommitted results, and no duplicate publication. -- Loss of only the plugin connection, loss of only the core connection, uncertain commit outcomes, cancellation/reclaim races, - and the core Scope gate preventing old-transaction reconnect/publication. -- Creation/modification/deletion evidence tied to actual revisions; increment on chunk removal, readable zero chunks, history. -- Source/document/knowledge-base deletion racing publication; tombstones deny derived reads before head/index cleanup. -- Delete a first-import queued/failed file without an Artifact, cascade over unpublished resources, and race deletion against - first publication; no fabricated deletion revision/evidence and no cancellation after a resource tombstone commits. -- Cancellation rejected after deletion effects; repeated deletes repair failed cleanup, concurrent retries share one active - successor, and completed objects do not get duplicate revisions/evidence. -- Direct active-model configuration edits rejected, Scope-wide switch/rebuild, partial-publication recovery, failed maintenance, - and old-profile job invalidation. -- Directory/single/batch chunk boundaries, complete index lifecycle, rebuild, and valid-candidate refill. -- OpenDAL snapshots accessible to Server/Worker; later original changes do not change accepted inputs. - -Mocks do not establish real backend/OCR support. Compare the two rules on a small corpus for answer-passage recall, SOP -integrity, and provenance without claiming measured quality or scale in this RFC. #2441 owns ingestion/resources, #2442 owns -queue/processing/publication, #2443 owns retrieval/APIs, and #2444 owns operation/acceptance. No new issues are required. +Use Markdown from a pinned oceanbase/oceanbase commit and real text images. Mocks cannot establish real OCR or backend support. +#2441 covers ingestion/configuration; #2442 framework consumption/parsing/publication; #2443 retrieval/edit APIs; #2444 operation +and acceptance; #2440 tracks the whole feature. Implementation may use one PR with staged commits and validation. No new issues. # Drawbacks -The plugin owns migrations, backup, and recovery for three domain tables and indexes. Separate storage requires reconciliation -and short commit gates. Complete chunk snapshots, successful operation evidence, soft deletion, and terminal jobs consume -storage. Resource kinds need explicit constraints. The first phase offers neither distributed transactions nor large-scale -performance guarantees, and index rebuild may affect multiple knowledge bases within a Scope. +Persistent infrastructure failures can block a Scope window; synchronous editing has request time limits. The plugin owns +three-backend indexes, migrations, and backups. Immutable results/history consume storage. Forget removes normal retrieval, +not history access or stored evidence; Sources remain immutable and readable. # Rationale and alternatives -- One business plugin owns membership, work, and configuration, while internal parsers remain independently extensible. -- Three plugin tables provide per-Source deletion and per-file jobs without changing core models. Two fixed resource kinds - avoid separate document-state/receipt tables. -- Sources hold immutable inputs/success evidence; jobs hold mutable execution state. Pending commands are not success Sources. -- Artifacts manage whole-document revisions and chunk rows support exact reads; editing old rows would destroy history. -- An independent queue supports slow parsing/external waits without existing consumption cursors, reusing only separable - Supervisor runtime tools. -- Prepare immutable results, publish core, then acknowledge the job to respect storage isolation; cross-store atomicity is not - a default capability. -- Deletion revisions provide stable operation evidence; head retirement and guards control visibility. Removing search entries - alone cannot delete content. +- Scope is the knowledge base, matching a single-family plugin without another Artifact or cross-family writes. +- Framework generate/cursor atomically commits Artifacts and consumption progress; the plugin records acceptance/observations + rather than duplicating scheduling. +- Generic synchronous PUT supplies preconditions and success evidence; plugin-route writes do not automatically have those semantics. +- Original and request Sources separate immutable facts from reprocessing; direct lineage and original provenance have explicit roles. +- Immutable chunk references preserve history and failure recovery; in-place body replacement cannot implement versioned editing. +- Forget follows framework lifecycle without Source tombstones, deletion revisions, or global read interception. # Prior art Builds on [plugin interfaces #2549](https://github.com/oceanbase/powercontext/pull/2549), [plugin APIs #2579](https://github.com/oceanbase/powercontext/pull/2579), [Source identity](1400_source_definition_and_observation_model.md), -[processing supervision](1515_artifact_processing_supervisor.md), and -[Source/Artifact APIs](1437_source_artifact_rest_api.md). Reuse original identity, Artifact revisions, successful operation -evidence, and governance while implementing independent knowledge-base jobs and chunk projections. Atomic Memory retirement -does not automatically provide Source cascades or plugin lifecycle guards. +[processing supervision](1515_artifact_processing_supervisor.md), and [Source/Artifact APIs](1437_source_artifact_rest_api.md). +Future collection can integrate [#2617](https://github.com/oceanbase/powercontext/pull/2617). Collection checkpoints describe +acceptance, not completed parsing; deleting a collection target does not delete its Sources or documents. # Unresolved questions -Before implementation, fix composite registration/constrained writer interfaces for the core Scope gate, generic read guards, -and exclusive Source consumption admission. Lock order is core Scope, plugin resources/jobs, then Artifact heads; backend -adapters must verify connection failures and compatibility with existing generic mutation paths. Implementation fixes OCR models, chunking defaults, -lease/concurrency/retry limits, API count/byte bounds, and concrete schema types without changing ownership or commit semantics. -Restoration/erasure, job archival and idempotency retention, rename identity, per-base vector spaces, and full edited-document -export require separate contracts. +Implementation fixes SQL/index details, OCR model versions, window/file sizes, synchronous editing limits, and API byte bounds. +Validate revision/lifecycle races on real backends. Check gaps between framework RFCs and implementations, including dedicated +storage and upgrades; proposals are not released capabilities. These choices do not change append-only Sources, forget without +new revisions, synchronous edits, pinned request bases, or independent models. # Future possibilities -Word/PDF/scene-image parsers reuse jobs, chunking, publication, and retrieval. External parsing persists a remote reference and -resumes by polling, without requiring a full parser framework initially. Further extensions include OpenDAL providers, rerank, -neighbor/parent-section context, and bounded multi-step retrieval. Their quality and costs require measurement rather than -being prerequisites for the first phase. +Word/PDF parsing, continuous collection, cross-base queries, rerank, adjacent context, in-flight cancellation, and controlled model +migration. Complete Source deletion, revoking historical access, knowledge-base cascades, and independent long tasks require +separate contracts rather than implicit first-phase promises. diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index 37f7325856..3e27dbee16 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -1,6 +1,6 @@ --- -title: "RFC 2570:Knowledge Base 文档知识库插件" -description: "以单个业务插件、独立持久任务队列和三张插件业务表提供文档知识库,不改变已有 Source/Artifact 表结构。" +title: "RFC 2570:基于 Scope 的 Knowledge Base 文档插件" +description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 document Artifact,支持三种数据库、同步 chunk 编辑及框架原生软删除。" --- - Proposal Name: `knowledge_base_plugin` @@ -11,471 +11,302 @@ description: "以单个业务插件、独立持久任务队列和三张插件业 # 概述 -以一个 `knowledge-base` 业务插件提供本地文档接入、解析切块、版本管理和混合检索。一个 Scope 内可以预创建多个 -`knowledge-base` Artifact;原文 Source 和整篇 `document` Artifact 各自独占归属一个知识库。复用现有 Source、Artifact、 -head 和 lineage 表,不改变它们的结构;插件新增资源登记、独立任务和 chunk 三张业务表。后台处理不使用原有 Source -消费 cursor。本文是目标设计,依赖插件框架扩展,不表示功能已经发布。 +一个 `knowledge-base` 业务插件提供本地文档接入、解析、切块、版本管理及混合检索。一个普通 Scope 对应一个知识库, +插件只声明 `document` family,每个 Artifact 表示整篇文档。知识库本身不是 Artifact;业务配置按 scope_id 保存于插件存储。 +插件附带原文和处理请求 Source 定义,后台复用框架 generate、Supervisor 和消费 cursor,不实现独立任务调度队列。 + +首期支持 SQLite、SeekDB、OceanBase,Markdown、独立图片 RapidOCR、规则切块、同步 chunk 编辑/移除和文档 forget。 +这是依赖框架契约的目标设计,不表示当前实现 PR 已提供全部能力。 # 动机 -业务说明和 SOP 需要原文保真、片段检索、可预测更新与删除。解析可能较慢或依赖外部服务,需要持久任务和逐文件失败恢复。 -业务插件应独立管理这些状态,不把知识库字段加入共享 Source 模型,也不通过一个顺序消费 cursor 阻塞其他文件。 -Artifact 继续管理整篇文档版本;chunk 明细与索引分离,避免读取大型正文 JSON。 +业务描述和 SOP 需要可检索片段、原文溯源以及不会覆盖历史的人工修改。Scope 提供知识库的授权和组织边界;Artifact 管理 +整篇文档版本;插件存储保存大块正文和索引。复用现有调度、版本前置条件与生命周期,可以减少知识库专有的运行机制。 # 使用层说明 -1. 通过通用 Artifact API 创建空 `knowledge-base`,再选择本地目录/文件导入。 -2. 导入返回持久任务 ID;界面可以显示排队、处理阶段、失败原因、完成结果及当前可用版本,不要求百分比。 -3. Markdown 和独立文字图片分别经过 Markdown 解析和 RapidOCR,统一切块、建立全文/向量索引后发布 document。 -4. 原文件变化或显式重新解析沿用 document ID,成功后发布新 revision;失败继续使用旧版本。 -5. 手动编辑或移除 chunk 也生成新 document revision,保留历史。检索可选择同一 Scope 内多个知识库。 -6. 删除只改变逻辑可见性,保留业务正文、原文快照和历史;普通、精确、历史、证据和检索入口均遵守删除规则。 +1. 管理员创建知识库 Scope,并保存解析/切块配置,然后导入 Server 可访问的本地目录或文件。 +2. 插件保存不可变原文快照、登记 Source,并提交处理请求 Source;导入接受不等于解析完成。 +3. 框架异步调用 generate,处理 Markdown/图片,准备完整 chunks 和索引,再发布 document。 +4. 内容变化或显式重解析沿用 document ID;失败保留已有版本。状态区分待处理、最近失败、已发布及冲突/跳过。 +5. 用户同步编辑或移除 chunk,document revision 增加,core 在同一事务记录 lineage_only 成功操作 Source。 +6. 文档软删除使用通用 forget:变为 deprecated、退出正常检索,不增加 revision。正文、原文和历史保留。 -首期覆盖 SQLite、SeekDB、OceanBase,支持本地 OpenDAL fs、Markdown、RapidOCR + ONNX Runtime、规则切块和人工编辑。 -Markdown 内图片保留引用,不自动抓取或 OCR。不要求几万篇规模测试。PDF/Office、场景图理解、远端上传/原文存储、 -定时目录同步、语义/LLM 切块、恢复/永久擦除、逐知识库 embedding 空间和无停机索引切换不在首期范围。 -任务状态接口属于首期;完整管理页面可以在相同契约上实现,不以调度效果图作为已实现能力。 +首期不承诺运行中撤销,不提供 Source 删除、知识库级联删除、物理擦除、独立任务队列、在线换模型、跨知识库聚合检索、 +持续目录同步或远端 runner。PDF/Office、复杂场景图、Markdown 内嵌图片 OCR、语义/LLM 切块和几万篇规模评测不在首期。 +恢复/合并方法首期不实现,对应通用入口按框架返回不支持;不能把导入当作恢复操作。 # 参考层说明 -## 1. 一个业务插件与命名 +## 1. 插件、Scope 与框架依赖 -插件统一注册专用文档 Source 类型、`knowledge-base`/`document` family、后台任务入口、自有存储迁移和 API。 -接入、解析、切块、检索是内部模块,不拆成独立安装的插件。方案依赖 [#2549](https://github.com/oceanbase/powercontext/pull/2549) -和 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 后续提供所需的复合能力注册、受限写入和 API 扩展;不把提案当作已发布接口。 +遵循 [#2549](https://github.com/oceanbase/powercontext/pull/2549) 的单 family、Source 定义、writer、模型和存储契约, +以及 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 的插件路由、Scope 管理和 upgrade 契约。 +[#2616](https://github.com/oceanbase/powercontext/pull/2616) 是实现依赖;其三后端专属存储等能力需要实际落地验证。 +[#2617](https://github.com/oceanbase/powercontext/pull/2617) 仅是后续持续采集的接入方向,不是本地显式导入的前置条件。 -| 位置 | 标识 | +| 对象 | 模型 | | --- | --- | -| 展示名 | Knowledge Base/知识库 | -| 插件与知识库 family | knowledge-base | -| 整篇文档 family | document | -| 归属/跨库选择字段 | knowledge_base_id/knowledge_base_ids | -| 模块与配置前缀 | knowledge_base | -| 插件表前缀 | pc_knowledge_base_ | +| 知识库 | 普通 Scope,scope_id 是知识库身份 | +| 插件 | knowledge-base,单个安装目录,单个 document family | +| 原文 | knowledge-base-file Source,固定快照及原路径 | +| 处理请求 | knowledge-base-process Source,固定原文引用、配置、base 和请求身份 | +| 文档 | document Artifact,整篇文档的有界 manifest | +| chunk | 插件存储中的不可变结果,不是独立 Artifact | ```mermaid flowchart TD - S[Scope] --> K1[knowledge-base K1] - S --> K2[knowledge-base K2] - K1 --> R[资源登记: 稳定文件身份] - R --> O[不可变原文 Source] - R --> J[独立 job] - O --> P[解析与规则切块] - J --> P - P --> C[不可变 chunk 结果与索引] - C --> D[document revision: 有界 manifest] - E[lineage_only 操作证据] --> D - D --> Q[知识库检索与精确 chunk 读取] + S[Scope: knowledge base] --> C[Plugin configuration] + S --> O[Original Source and immutable snapshot] + O --> R[Processing request Source] + R --> G[Framework generate and cursor] + G --> I[Immutable chunks and indexes] + I --> D[document Artifact revision] + U[Synchronous chunk edit] --> D + D --> Q[Retrieval and exact chunk reads] ``` -Scope 保持授权边界。知识库 Scope 的业务内容只包括文档 Source、document 和 knowledge-base;操作证据是内部记录。 -所有归属都显式保存并核验,不从 tags 或 lineage 推断。文档原文只供 document 管线处理;原文不是 lineage_only。 -框架的消费准入必须覆盖写入通知、启动恢复扫描、自动消费和手动生成,不能只靠 Source 类型名称或不发送唤醒来隔离。 -同库部署依赖这些通用扩展点,不默认另建 PC Server;尚未实现准入之前不能宣称隔离有效。 - -插件独立持有 embedding/索引配置,可在安装时从兼容主路径初始化,此后不自动跟随。密钥保持在部署配置中。 -首期同一 Scope 的 document 共用插件 profile,解析/切块可按知识库配置;模型和索引配置固定进任务及结果元数据。 -当前 profile 引用保存在 knowledge-base Artifact 配置,同 Scope 的有效知识库必须一致,新建知识库继承该引用。 -环境变量只提供初始默认值,不能覆盖已有数据的活动 profile。更换模型只能执行 switch_model_and_rebuild,覆盖整个共享 Scope,见 8.1。 +通过 ctx.scopes.create 创建 Scope,沿用 server.admin 要求;同幂等键返回同一 Scope。框架的插件外部引用标识创建归属。 +标题/摘要使用 Scope 字段,业务配置使用插件表。Scope 创建成功但配置失败时,重试补齐配置;配置未就绪时拒绝导入。 +授权沿用 Scope read/contribute、Artifact write 及框架版本校验,插件接口不得将 Scope 贡献权限等同于任意文档修改权限。 -## 2. OpenDAL、身份与去重 +插件 inputs 只订阅处理请求 Source,原文不会重复触发本插件生成。知识库 Scope 按部署约定专用,不启用其他内容消费者; +不宣称 Source 类型名称提供框架级排他隔离,其他消费者的准入能力不属于本插件的保证。 -首期只接受插件运行环境可访问的本地目录。导入进程、Server 和 Worker 通过相同存储别名访问受管不可变快照目录, -可使用本机容器卷映射。OpenDAL fs 提供本地读取,不会让远端客户端路径自动可访问。拒绝根目录越界,固定符号链接策略。 +## 2. 本地存储、身份与请求接受 -Source 记录 `original_path` 作为出处,`snapshot_ref` 包含 store_id、object_key 和 digest。先保存快照并对实际字节计算 -SHA256,再持久接受任务;解析只读快照,不读可能已变化的原文件。mtime/size 只用于提示,不能代替内容 hash。 +OpenDAL fs 管理 Server、导入进程和 Worker 均可访问的本地快照目录。原路径只作出处,解析只读快照。 +拒绝根目录越界并固定符号链接策略;先写快照,对实际字节计算 SHA256,再登记 Source。mtime/size 不能代替 hash。 ```text -file_key = (scope_id, knowledge_base_id, collection_id, normalized_relative_path) -document_id = stable_hash(identity_version, file_key) -source_key = stable_hash(source_schema_version, file_key, raw_content_digest) -processing_key = hash(parser/OCR/model/normalizer/chunker versions and settings) -index_key = hash(complete embedding inputs, plugin profile and projection versions) +file_key = (scope_id, collection_id, normalized_relative_path) +document_id = stable_hash(identity_version, file_key) +source_key = stable_hash(source_schema_version, file_key, raw_content_digest) +request_key = (scope_id, idempotency_key) +result_id = digest(canonical complete chunk result and provenance) ``` -Collection 从存储实例和规范化根目录派生,与本次扫描/任务 ID 无关。核对完整身份以处理摘要碰撞,不截断路径。 -Source payload 固定归属、document ID、文件身份、media type、摘要和快照;重放不重写采集时间等 canonical 信息。 - -| 情况 | 行为 | -| --- | --- | -| 同请求键、同参数 | 返回同一任务/确定结果;同键不同参数返回冲突 | -| 同文件字节/配置且有可用结果 | 复用 Source/document,检查索引是否可用,不重复解析 | -| 不同请求键命中相同活跃目标 | 返回 409 和已有任务引用,不创建重复执行 | -| 原文字节变化 | 新 Source,同 document ID,新目标代次和任务 | -| 显式重解析/切块配置变化 | 复用 Source 与 document ID,成功发布新 revision | -| 仅 embedding/索引变化 | 从已提交 chunks 重建,不重复 OCR | -| 同字节不同路径/知识库 | 不同逻辑 Source/document,可共享物理快照 | -| 存在人工编辑 | 普通重复导入保留编辑;重新解析必须明确 manual_edits_policy=discard | - -Source 已存在不等于处理成功。文件回到旧字节可引用较早 Source,期望输入以资源登记中的最新目标为准,不以 journal 顺序为准。 -改名首期视作新文件,目录消失不自动删除;已删除身份不因重导入静默恢复。显式 reprocess 不因结果相同而当作普通导入跳过。 +Collection 从存储别名和规范化根目录派生,不取自扫描批次;保存完整身份以检查 hash 碰撞。同文件跨 Scope 是独立逻辑文档。 +同路径同字节复用原文 Source;变化产生新原文 Source,但 document ID 不变。改名视作新文件,文件消失不自动 forget。 -## 3. 轻量解析与切块 +每次处理请求固定 original_source_ref、snapshot_ref、处理配置、独立模型指纹、base_revision、manual_edits_policy 及请求摘要。 +已有文档固定接受时的 revision;首次生成使用明确的无 head 前置条件。普通重复导入有可用同内容/配置结果时直接复用; +显式重解析或失败重试使用新的请求键,即使原文相同也产生新的处理请求 Source。人工修改不被普通导入覆盖;丢弃修改必须显式 discard。 -解析器入口只需接受快照引用和固定配置,输出 Markdown、来源定位及可选警告。内部格式注册表选择 Markdown 或图片解析器; -后续格式增加解析器和测试样本即可,不要求通用文档 AST、解析器能力协商或独立解析插件系统。 -解析器不写 Artifact、任务状态或索引;外部服务适配可以返回待完成引用,由任务执行层保存并继续。 +插件资源行先保存有界、不可变的接受参数,再幂等登记原文和处理请求 Source,最后记录实际 SourceRef。 +框架可能在插件确认字段写入前调用 generate,因此执行依据是已提交请求 Source 和固定接受参数,不等待额外的 ready 标记。 +只在处理请求 Source 确认持久化后返回 accepted。任一步响应丢失,用相同请求键及参数补齐登记;相同键不同参数返回冲突。 +插件登记不是任务队列,未成功登记 Source 的请求不承诺后台执行;调用者可重试原请求。未引用快照不形成可检索内容。 -Markdown 使用 markdown-it-py 提取结构和来源映射。图片使用 RapidOCR + ONNX Runtime,保留文本框、顺序、置信度及预处理坐标变换, -整理成 Markdown,但不猜测复杂标题、表格或流程图语义。规范化文本位置映射回原图,声明定位精度;派生 Markdown 不替换原文 Source。 +目录导入按有限文件批次调用同一逐文件接受流程,返回逐项回执;枚举完成不是全部解析完成。首期不保存独立目录扫描任务, +大目录通过客户端分批提交,失败后重复枚举仍按文件身份及请求键去重。 -- 默认按标题/内容块组织,再对超长块递归切分;缺少可靠标题时按段落/句子递归切分。 -- 代码、表格和列表步骤尽量完整;超长表格按行拆分并保留表头,超长代码保留语言和续块标记,仍受硬上限限制。 -- Overlap 用于拆开的长段落,不机械跨章节重叠;中文使用句号/分号等边界。 -- 保存标题路径和原文定位;embedding 输入包含标题时,按完整输入检查模型 token 上限,不能把字符数等同于 token 或静默截断。 -- 参数包含 max_chunk_chars、overlap_chars;1200/100 仅为待验证示例,不是质量结论。 -- 校验 UTF-8、图片解码/像素上限、模型版本和资源限制;OCR 无文字显式失败,不伪装成功空文档。 +## 3. 解析、切块与原文溯源 -规则保持确定、可测试。修改切块配置可复用可验证的解析结果;不要求首期建立复杂阶段缓存。 +Markdown 使用 markdown-it-py 提取标题、段落及来源位置。独立图片使用 RapidOCR + ONNX Runtime,保留文本框、顺序、 +置信度及坐标变换,整理成 Markdown 后走相同切块流程;不猜测复杂表格或流程图语义。内嵌图片只保留引用。 -## 4. 持久化与关系 +默认按标题和内容块切分,超长块递归按段落/句子切分。代码、表格和 SOP 步骤尽量完整,超长表格保留表头;overlap 仅用于 +被拆开的长段落。max_chunk_chars/overlap_chars 可配置,1200/100 只是初始验证值。完整 embedding 输入包含标题等附加文本, +必须按模型 token 上限检查,不能静默截断。UTF-8、图片尺寸、解码及 OCR 无文字等错误明确报告。 -### 4.1 现有表原样复用 +解析器只返回 Markdown、locators 和警告,不管理 cursor 或 Artifact。后续格式通过内部解析器注册表扩展,不新增插件类型。 -| 表 | 职责 | -| --- | --- | -| pc_sources | 不可变原文引用、成功人工/删除操作的 lineage_only 证据;不增加列 | -| pc_artifacts | knowledge-base 配置、document manifest、不可变 revision | -| pc_artifact_heads | 当前 revision、lifecycle_state、governance_generation | -| pc_scopes | 复用既有 Scope 行作为 core 短事务互斥点,不改字段或借用 version 作为任务计数 | -| pc_artifact_lineage_sources/pc_artifact_lineage_artifacts | 精确版本的输入/操作证据和 base 引用 | -| 既有权限、tags 和引用设施 | 复用公共语义,不承载无界任务或成员 JSON | +处理请求记录原文 SourceRef 和快照引用。generate 的直接 source_refs 只引用当前窗口的处理请求;已消费原文未必出现在窗口中, +不能绕过 writer 的引用限制。Document manifest 保留原文引用,形成“document → 请求 Source → 原文 Source”的可检查溯源链, +不宣称原文总是每次 revision 的直接 lineage。同步编辑保留当前 lineage 及原文定位,并新增 core 的成功操作 Source。 -原有 processing intents、cursor、lease、binding state 表不用于本插件任务,不增加知识库字段或记录。 -Source journal 可保留为原有持久化约束的一部分,但不驱动知识库任务发现或完成。 +## 4. 插件存储与模型 -### 4.2 三张插件业务表 +ctx.storage 使用与 Server 相同的后端:SQLite 为独立文件,SeekDB/OceanBase 为插件专属库。建库权限不足时由部署者预建。 +插件通过 backend 选择迁移及全文/向量实现,不修改现有核心表。原文件仍在 OpenDAL 本地目录,不塞进 SQL 正文列。 -表属于插件专属存储,由插件迁移;复用 SQLite/SeekDB/OceanBase 连接和适配能力。全文/向量辅助结构不计入业务表数。 - -| 表 | 关键字段与约束 | +| 插件业务表 | 字段及约束 | | --- | --- | -| pc_knowledge_base_resources | scope_id、knowledge_base_id、resource_kind、resource_key、document_id、source_ref、identity_payload、lifecycle_state、deleted_at、target_generation、current_job_id | -| pc_knowledge_base_jobs | job_id、scope_id、knowledge_base_id、document_id、operation、idempotency_key、request_digest、input_snapshot、target_generation、base_revision、state、stage、attempt、next_run_at、execution_token、lease_owner、lease_expires_at、error_code/summary、external_task_ref、result_id、result_revision、result_kind、parent_job_id、checkpoint、cleanup_cursor | -| pc_knowledge_base_chunks | scope_id、knowledge_base_id、document_id、result_id、chunk_id、ordinal、text、text_length、content_digest、heading_path、source_locator、origin、edit_metadata | +| pc_knowledge_base_resources | 主键 (scope_id, resource_kind, resource_key);固定三类 scope/document/request;有界 payload、request_digest、source_ref、document_id、最近处理观察及时间 | +| pc_knowledge_base_chunks | 主键 (scope_id, document_id, result_id, chunk_id);ordinal 同结果唯一;text、text_length、content_digest、heading_path、source_locator、origin、edit_metadata | -Resources 只支持两类固定记录,不是通用对象平台: +Resources 是固定用途登记,不是通用任务框架:scope 行保存配置/版本;document 行保存稳定文件身份;request 行保存不可变接受参数、 +幂等回执及最近尝试结果。它没有租约、执行 token、领取队列或清理 cursor,也不复制 Artifact 的发布指针与生命周期。 +请求结果可以引用精确 revision 供对账,成功事实仍以 core 为准。全文/向量辅助结构属于派生索引,不计入业务表数。 -- `document`:每个稳定逻辑文件一行,首次解析前创建;保存路径身份、当前目标和删除标记,不要求提前创建空 document Artifact。 -- `source`:每个原文 Source 一行,保存归属及独立删除标记;不把所有版本塞进一行 JSON。成功操作证据由其目标 Artifact 的可见性控制。 +Document content 只保存标题、原文 SourceRef、文件身份、result_id、chunk 数量/摘要、配置指纹、人工修改标记和 applied_request_ref。 +正文及无界 chunk ID 列表不进入 manifest。结果 ID 来自规范化完整结果,不能用尚未提交的 revision 号作为存储键。 -主键为 `(scope_id, knowledge_base_id, resource_kind, resource_key)`。Document key 来自 file_key,Source key 包含完整 SourceRef 身份摘要; -保存并比较完整身份,校验同一 Source 不跨库归属。SourceRef 必须包含 source_type 和 source_id。仅 document 行使用目标代次/当前任务字段。 -资源删除是单向标记;已发布 revision 只读 Artifact head,不再复制一个发布指针。公共时间字段和有界错误/JSON 的存储类型由实现固定。 +模型由插件独立配置和创建客户端,密钥来自部署配置,不存入 Source/Artifact。不自动跟随 ctx.models 或 Server 模型变化。 +同一插件首期使用一个固定 embedding profile,包含模型身份/版本、维度、完整输入规则与规范化版本;维度相同不等于模型相同。 +已有索引与部署 profile 不一致时拒绝向量查询及新发布,明确要求受控迁移,不自动覆盖配置或混用向量。 +首期不提供在线换模型操作;同 profile 的索引修复从已提交 chunks 重建。解析/切块配置可按 Scope 保存并固定到请求。 -Jobs 对 `(scope_id, knowledge_base_id, operation, idempotency_key)` 建唯一约束,请求摘要覆盖全部业务参数和前置条件。 -索引覆盖到期任务、过期租约、document 和知识库归属。目标行串行化同文档请求,不依赖跨后端不一致的条件唯一索引。 -终态任务保留幂等回执;不另建回执/attempt 表,有限错误和 attempt 计数足够首期展示。 +## 5. 框架消费、状态与失败处理 -Chunks 主键为 `(scope_id, knowledge_base_id, document_id, result_id, chunk_id)`,同结果 ordinal 唯一。 -`result_id` 在 core 分配实际 revision 前标识不可变结果,不能猜测下一个 revision 后写入。 -完整结果保存独立分块快照,向量属于派生索引。`text_length` 为 Unicode 码点数量。 +声明 on_sources 和处理请求 inputs,复用框架 generate/Supervisor、Scope binding、消费 cursor、租约 fence 和失败退避。 +没有独立 jobs 表,也没有插件自建 Worker 调度器。每次调用最多一个 writer.transaction,Artifact、cursor 和调用确认在 core 同事务提交。 +配置小的 max_sources 和有界文件大小,避免一次窗口包含过多 OCR/模型工作;不承诺任意大小文件都能在框架时限内完成。 -Document manifest 有界保存标题、knowledge_base_id、文件身份、root SourceRef、result_id、chunk 数量/摘要、处理/索引指纹、 -人工修改标记、applied_job_id 及必要操作摘要,不嵌入正文或无界 chunk ID 列表。精确 revision 通过 manifest 找结果;历史不依赖当前索引。 +| 事件 | 行为 | +| --- | --- | +| 请求已提交、尚无结果 | 展示待处理,不虚构百分比 | +| 文件格式错误、无文字等确定输入错误 | 保存有界失败观察,跳过该输入;窗口正常确认后继续后续请求 | +| 数据库、模型服务、索引持久化故障 | 抛出异常,core 回滚,cursor 不前进,由框架退避重试 | +| 固定 base 已变化或文档已非 active | 记录冲突/跳过,不以新 base 自动覆盖;用户重新提交请求 | +| core 发布完成 | 从 manifest/历史中的 applied_request_ref 判定已发布及精确 revision | +| 发布成功但插件状态未更新 | 根据 core 对账,不能仅凭缺少状态把它判为失败或重复发布 | -## 5. 独立队列与状态机 +资源表的失败是最近尝试观察,不等于 cursor 已确认;不能仅凭插件状态推进消费或跳过尚未证明完成的 core 写入。 +基础设施持续故障可能阻塞该 Scope 的后续窗口,这是复用框架的边界,不承诺独立逐文件无限制并发或死信队列。 +确定输入失败的人工重试使用新请求;旧 Source 不修改。处理请求是意图,不是 lineage_only 成功证据。 -```mermaid -stateDiagram-v2 - [*] --> queued - queued --> running - running --> succeeded - running --> retry_wait - retry_wait --> running - running --> waiting_external - waiting_external --> queued - running --> failed - queued --> cancelled - running --> cancelled - waiting_external --> cancelled - retry_wait --> cancelled - queued --> superseded - running --> superseded - waiting_external --> superseded - retry_wait --> superseded -``` +首次发布前确认无 head;更新核对固定 base、原文、人工修改策略和生命周期。框架重试也不能改写请求中的 base 或丢弃策略。 +事务外准备后发生编辑/forget 时,发布使用框架的 revision/治理并发校验;不能自动恢复 deprecated 文档。 +若实现不能在竞争中保护生命周期,必须修复框架适配并通过测试,不能用插件内存锁代替或承诺已支持。 -`stage` 与状态独立:ingest、parse、chunk、index、publish、cleanup。等待外部服务的任务保存远端引用/next_run_at 后释放 Worker; -到期查询继续,不长期持有进程或事务。远端提交使用稳定幂等键;服务不支持幂等时需对账,不能承诺外部调用恰好一次。 +## 6. 发布与索引一致性 -KnowledgeBaseTaskSupervisor 只扫描插件 jobs,负责领取、心跳、过期回收和确认。可复用已有进程启动/终止、预算和关闭工具; -不接入原有 Scope/binding discovery、intent 或 Source cursor。若现有 Supervisor 与这些机制耦合,则实现轻量插件调度器, -不为复用而把逐文件任务塞回旧表。每个 document 串行发布,不同文档有界并发。 +1. 在 core 事务外完成解析、向量计算;持久保存不可变 chunks 及其全文/向量索引,校验数量、摘要和可读取性。 +2. 在 writer.transaction 中校验前置条件并 put manifest,引用 result_id 与索引指纹;generate 同时提交 cursor,用户编辑同时提交证据。 +3. core 提交失败时准备结果不可见,旧 manifest 和旧索引保持可用;重试不原地覆盖旧结果。 +4. 检索候选必须匹配当前 active document 的 result_id 和 profile;过滤后补取,未发布结果不能占满 top-k。 -`target_generation` 表示用户期望哪个结果,`execution_token` 表示同一任务哪次执行拥有资格。领取、续租和状态更新均条件校验 token; -新目标使旧目标 superseded,租约恢复更换 token。SQLite 使用实际支持的事务/CAS,不假设所有后端均支持 SKIP LOCKED。 +索引按结果隔离,不以单一 document_id 覆盖旧有效候选。模型和文件计算不进入短事务,不新增 core Scope 行锁协议或跨库事务。 +历史 chunk 通过精确 revision 的 manifest 定位,不依赖当前搜索索引。仅保留未引用的准备数据不会改变可见结果,永久清理另定。 -普通请求在授权及生命周期检查后先识别同键重放,再检查新请求的当前 base,避免成功重试被旧 ETag 拒绝。 -删除入口允许授权调用者再次访问已删除目标的有限状态以补齐清理,不能先用通用 410 阻断该入口。 -终态任务不复活;自动有限重试属于同一任务,普通处理的人工重试使用新幂等键/job。删除善后按第 7 节由再次删除自动创建新 job。 -取消不回滚已发布结果;任何删除墓碑或 retirement 一经提交,相关删除/善后工作不可取消。状态机的 cancelled 边受此条件约束。 -编辑/移除固定 base,有冲突的活跃变更时拒绝,不静默排队或换基准。逐文件失败不阻塞整个 Scope。 +## 7. 同步 chunk 编辑与软删除 -## 6. 接受、发布与跨存储恢复 +编辑和移除 chunk 通过通用 Artifact PUT 交给 update_artifact,同步完成;不是插件 API 写入,也不排队。 +插件的编辑载荷定义为有界 chunk 变更描述,包含 chunk ID/新文本或移除动作;服务端读取对应基准版本,合成完整结果, +只由服务端产生 manifest,拒绝客户端指定任意 result_id 或原文归属。Core 允许插件规范化提交内容;不开放任意 manifest 替换。 -Core 与插件专属存储不共享事务,不能声称 Source、任务、chunk、索引和 Artifact 一次原子提交。 +带 If-Match,先生成新结果及索引,再恰好一次 put(expected_revision=...)。Core 同事务保存提交的编辑载荷作为 lineage_only +Content Source,document revision 增加。修改保留逻辑 chunk ID 和原定位,标明人工文字并非原文逐字引用;移除最后一块允许零块版本。 +新正文可能出现在编辑证据中,沿用现有权限,不宣称 forget 会抹除这些证据。 -| 边界 | 行为与恢复 | -| --- | --- | -| 快照 | 保存不可变原文字节;未接受的孤立快照不是可见内容,永久清理另定 | -| 插件接受事务 | 校验/锁定资源目标,幂等检查,保存固定输入与任务;202 后任务可恢复 | -| Source 登记 | Worker 在 ingest 阶段幂等保存/复用 Source;Source 写成功而任务未确认时可重试,不漏任务 | -| 事务外计算 | 固定快照与配置,解析/OCR/切块/embedding,不持有数据库锁 | -| 插件结果准备 | 保存不可变 result_id 对应的完整 chunks 和可用索引,核对数量及摘要,未被 manifest 引用的结果不可见 | -| Core 发布短事务 | 校验 base、归属和执行资格;提交 document revision、必要操作证据 Source、lineage 和 head | -| 插件完成事务 | 写实际 result_revision 和 succeeded;若确认丢失,按 applied_job_id/result_id 对账,不重复发布 | - -提交闸门由 core 提供,复用 `pc_scopes` 中已存在的 Scope 行。OceanBase/SeekDB 使用同一 core 事务中的行锁, -SQLite 使用 core 数据库的 `BEGIN IMMEDIATE` 写事务;不新增锁表、不改 Scope 字段。发布、删除、接受新目标、取消、 -领取/更换执行 token、租约回收及模型切换控制都必须先取得该闸门,再按固定顺序锁定插件资源/job,最后操作 Artifact head。 -普通心跳只按 token 续租,不改变执行所有权;接入和同步 Artifact 修改入口也不得绕过闸门。 - -取得两侧锁后重新读取目标、token、租约、Source 墓碑、父知识库生命周期和 core 已发布结果。发布始终在持有 Scope 锁的同一 core -连接/事务中完成,不能转交另一个无锁连接。取消/换目标/重领先在闸门内对账,再提交插件状态,完成后才释放 core 锁。 -发布路径则先提交 core,再补记插件成功;补记失败按确定结果恢复。这仍是分开提交,不是跨库原子事务。 - -插件数据库连接丢失时,core 锁仍阻止另一执行者取消或重领;core 连接丢失时,该事务不能再用于发布。 -任一连接报错或提交结果不确定,都退出当前尝试,禁止自动重连后沿用旧资格。恢复必须新取 core 闸门,再对账、重验插件状态。 -所有控制路径都遵循 core 在前、插件在后的锁顺序;不能在持有插件锁时反向等待 core 闸门。 - -该方案将同 Scope 的短提交串行化;解析、OCR、向量计算、索引构建和目录枚举在锁外并发进行。 -闸门内不做模型调用、DDL 或长时间计算。三种后端验证真实锁/连接失效和超时行为,不用内存锁或仅一次 token 检查替代。 -准备结果不可原地覆盖;重算不同内容使用新 result_id。普通发布失败保留旧 head 和可用旧索引。 - -## 7. 操作证据、编辑与软删除 - -成功创建/修改/删除 Artifact 需要对应的系统 `lineage_only` Source,关联实际输出 revision,不能用排队请求冒充成功证据。 -复用既有创建/替换证据语义;删除/移除的具体动作及原因保存在有界操作摘要中,不擅自假设核心已有新的 operation 枚举。 -任务是意图与执行记录,操作 Source 是成功事实,两者通过 job/operation ID 关联。 - -| 操作 | 版本和可见性 | -| --- | --- | -| 创建/配置 knowledge-base | 创建或新增配置 revision,关联操作证据 | -| 解析/重解析 document | 同 document ID 发布新 revision,lineage 关联原文;人工触发的变更保留操作证据 | -| 编辑 chunk/移除 chunk | document revision +1,完整新结果;关联成功操作证据,旧行不删 | -| 删除 document/knowledge-base | 新增含有界删除摘要的删除 revision,并在同一个 core 事务 retire head;关联删除证据 | -| 删除原文 Source | 标记 source 资源后立即阻断其原文及派生内容读取;document retirement、删除证据和索引清理由后台最终补齐 | - -删除整个 Artifact 生成 revision 是本插件的业务约定,不改变其他 family 的治理规则。删除 revision 可复用之前的 result_id, -无需复制 chunk 正文。操作摘要必须使删除 revision 真正写入,不能被“相同 content 的 put 是 no-op”跳过。 -证据、lineage、revision、head 在 core 同事务提交;失败不产生成功证据。同一已接受操作重放不增加 revision。 - -删除必须区分“已有 document Artifact”和“从未发布 Artifact 的逻辑文件”。在既有 core Scope 闸门及插件资源/job 锁内, -重新读取 head 并对账发布结果后选择分支:已有 head 按上述 revision/retirement 协议处理;确认从未发布时,删除逻辑文件只标记 -其 document 资源并使待发布任务失效,不要求 Artifact ETag,不创建空 Artifact、删除 revision 或 Artifact 成功操作证据。 -知识库级联也必须处理这些未发布资源。删除 Source 只标记指定 Source 并使依赖它的任务失效,不 retire 不存在的 document, -不删除无关 Source 版本;单独删除 document 仍保留原文 Source 可读。曾经发布但 head 缺失属于一致性错误,不能按未发布分支跳过。 -资源墓碑和任务失效须在释放闸门前提交,避免判断无 head 后后台又完成首次发布。Job 记录完成,重复删除不虚构 Artifact 动作。 -资源墓碑一经提交即属于删除生效,即使尚无 Artifact,也不能再取消该删除。 - -手动替换文字可保留逻辑 chunk ID,但引用必须带 revision;重切块可产生新 ID。人工正文标记非原文逐字引用,保留原始定位与编辑依据。 -移除最后一块允许零 chunk 结果,当前检索无命中。重复导入不得覆盖人工修改,显式重新解析需要 discard 授权。 - -删除 knowledge-base 先提交父对象删除 revision/retirement,立即阻断全部子内容;接受的 cleanup job 可在进程重启后继续, -分批标记 Source、删除 document、取消处理任务。每个真正变化的 Artifact 生成自己的证据,使用共同 operation ID 关联级联。 -Cleanup 是已删除父对象下的允许操作,不能被普通处理任务的父状态检查取消。清理游标只用于插件分批操作。 -先持久接受删除/清理 job,再提交第一个删除标记。资源墓碑或 Artifact retirement 一旦提交,删除进入不可取消阶段; -后续错误只能恢复善后,不能报告“已取消”并遗留半完成删除。尚未产生删除效果的排队任务仍可取消。 - -删除 document 保留原文 Source 可读;原文读取不因 document 单独删除而失效。删除未发布替代 Source 保留基于其他原文的旧版本。 -S1 对应旧 revision、S2 对应完整新解析时,删除 S1 不删除仅依赖 S2 的当前版本,但依赖 S1 的历史读取失效。 -Source 删除入口返回已生效回执(包括 202 清理中)前必须提交墓碑;仅接受 job 不等于已经删除。 -Source 墓碑提交是该原文及其派生内容的可见性截止点。此后开始的 document/chunk/历史/证据读取和检索都必须检查墓碑, -即使 document head 仍 active 或索引条目还在,也不能返回对应内容。删除开始前已返回给客户端的内容不作撤回保证。 -只允许 document retirement、删除 revision/证据及索引维护最终一致,不允许在等待后台清理时继续暴露内容;检查服务不可用时关闭读取。 -资源标记与 Artifact retirement 可分阶段完成,读取同时检查适用的父对象、document、精确 root 和 Source 标记。 -通用 Source、Artifact 精确/历史和证据读取需要框架可见性扩展点;仅插件检索过滤不满足删除契约。归属登记缺失时拒绝读取,不回退为无约束内容。 -受控内部恢复可以读取 retired 历史以对账;授权管理入口可查看删除后清理任务的有限状态,不开放正文或公共绕过参数。 - -再次删除复用同一个删除入口/operation,不新增 repair/retry API。鉴权后允许检查已删除目标的原删除记录和清理状态, -不因删除标记或原来的 ETag 已过时而直接拒绝善后;尚未删除的目标仍执行正常前置条件。重复请求参数冲突仍返回 409。 - -以下善后规则针对已经产生删除效果的操作。若首次删除在生效前失败或取消,再次删除按正常前置条件接受新删除任务;同幂等键仍重放原回执。 - -| 再次删除时的状态 | 返回和动作 | -| --- | --- | -| 首次删除或清理 job 仍活跃 | 返回同一删除操作标识与当前 job,202;不重复创建 | -| 清理未完成、上一次 job 已 failed/终止 | 后台创建新的 cleanup job,parent_job_id 关联原删除 job,202;旧任务不复活 | -| 所有清理已完成 | 200 already_deleted;不新增任务、revision 或证据 | +模型调用受同步时限及编辑大小限制,失败不发布半成品。提交响应未知时重新读取当前 revision/lineage;原 If-Match 不再满足时 +不能盲目重试。通用 PUT 不另承诺幂等键或恰好一次 HTTP 执行。 -在 core Scope 闸门内串行检查和创建后继任务,避免并发重复删除产生多个善后任务。新的内部 job 使用新的派生幂等键, -原客户端删除请求的身份和输入不变;响应可更新 cleanup_job_id/状态,但稳定关联同一次删除操作。 -清理按已提交墓碑、Artifact 删除摘要和原 operation ID 对账,跳过已完成对象;只为尚未实际修改的 Artifact 生成删除 revision/证据。 -该规则覆盖 Source、document 和 knowledge-base。已删除父对象仅允许这些受授权善后行为,不恢复普通写入或内容读取。 +整篇文档使用通用 forget,调用 forget_artifact,恰好一次 set_lifecycle(deprecated)。这只是生命周期变更:不追加内容 revision, +不生成本插件专有的删除证据,也不物理清理正文/索引/快照。正常检索及 Prepared Context 排除 deprecated 文档。 +通用 get、历史和证据沿用框架可见性;授权的精确 chunk 读取与 rendering 可展示保留版本,不返回“所有内容均已删除”的承诺。 +生命周期以 core 为准,不在插件表另建 document 墓碑;物理索引清理不是 forget 生效条件。 -## 8. 接口与检索 +已忘记文档不因重复导入、重解析或迟到处理自动恢复;同步编辑仅允许 active 文档。尚无 document Artifact 时没有 forget 目标, +首期不支持运行中撤销导入,不创建空 Artifact 或删除 revision。原文 Source 不提供删除接口;不提供知识库级联删除, +不能将物理删除 Scope 当作软删除。重复 forget 使用框架现有前置条件及 no-op 语义,不启动清理任务。 -复用 Source 编码/身份/校验、Artifact CRUD/history/tags、认证、权限、ETag、分页、引用与错误封装。 -文件导入使用插件 Source 接受能力,不能直接调用会触发旧消费者的写入路径。耗时编辑经插件任务接口返回 202; -不把同步 Artifact PUT 悄悄改成异步成功。通用写入不得绕过任务、版本、证据和删除规则。 +## 8. 接口、检索和权限 -路由为建议契约,插件 API 挂载遵循 #2579,实际注册语法随框架实现固定: -`P=/v1/plugins/knowledge-base/api/scopes/{s}`,`D=/v1/scopes/{s}/artifacts/document/{d}`。 +令 `P=/v1/plugins/knowledge-base/api`,`D=/v1/scopes/{s}/artifacts/document/{d}`。插件路由通过 PluginApi/Route 声明, +使用框架支持的响应能力;以下 accepted 是业务状态,不假定插件接口已经支持自定义 HTTP 202。默认成功 JSON 可返回 200。 -| 操作 | 接口/返回 | +| 操作 | 接口和返回 | | --- | --- | -| 创建知识库 | POST `/v1/scopes/{s}/artifacts`,family=knowledge-base | -| 知识库/document 概览与历史 | 通用 Artifact GET/revisions,返回有界 manifest | -| 导入本地文件/目录 | POST `P/imports`,显式 knowledge_base_id、root/paths 和 idempotency_key;202 任务回执 | -| 重解析/编辑/删除 | POST `P/jobs`,类型化 operation、固定目标和前置条件;再次 delete_source/delete_document/delete_knowledge_base 自动补齐清理,cleanup 仅供内部使用 | -| 更换模型并重建索引 | POST `P/jobs`,operation=switch_model_and_rebuild,显式确认同 Scope 的影响范围;复用任务状态接口 | -| 任务列表/详情 | GET `P/jobs`、GET `P/jobs/{job_id}`,分页、阶段、状态、有界错误、成功 revision | -| 取消 | POST `P/jobs/{job_id}/cancel`,仅未发布且未提交删除效果的非终态工作;模型切换发布开始后也不可取消 | -| chunk 目录 | GET `P/documents/{d}/revisions/{rev}/chunks`,分页元数据,不含正文 | -| 单个 chunk | 上述路径追加 `/{chunk_id}`,正文、出处、人工修改信息 | -| 批量 chunk | 上述路径追加 `/batch-get`,POST 有界 chunk_ids | -| 混合检索 | POST `P/retrieve`,knowledge_base_ids、query、mode、limit,返回 chunk 命中 | - -插件 chunk 路由使用与 Artifact 相同的 document ID/revision。路径从通用 Artifact 路由中分离,读取语义仍是精确 revision, -通过该 revision 的 manifest 解析 result_id,不回退当前 head。Directory cursor 绑定 Scope/document/revision,按 ordinal 排序。 -Batch-get 要求非空、无重复 ID,按请求顺序返回;先授权父对象,任一 ID 不存在则整批 404。限制 ID 数量及响应字节数,超限拒绝, -不截断正文。已删除对象授权后返回 410,零块版本目录为空。 - -创建知识库: +| 创建知识库 | POST `P/knowledge-bases`,调用 ctx.scopes.create 并保存配置;返回 scope_id | +| 导入文件 | POST `P/scopes/{s}/imports`,有界 paths、idempotency_key;返回逐文件请求 SourceRef | +| 重解析/重试 | POST `P/scopes/{s}/documents/{d}/reprocess`,base、固定配置、原文引用、新请求键 | +| 处理状态 | GET `P/scopes/{s}/imports/{request_id}`,接受记录、最近尝试及可核实的发布结果 | +| 文档概览/历史 | 通用 Artifact GET/revisions,返回有界 manifest | +| 编辑/移除 chunk | PUT `D`,If-Match,同步返回新 document revision | +| 文档软删除 | POST `D/forget`,revision 和 state_version;遵循框架响应 | +| chunk 目录/正文 | GET `P/scopes/{s}/documents/{d}/revisions/{rev}/chunks`,追加 `/{chunk_id}` 获取正文 | +| 批量 chunk | POST 上述目录路径追加 `/batch-get`,有界 chunk_ids | +| chunk 混合检索 | POST `P/scopes/{s}/retrieve`,返回精确 revision、chunk ID、分数及出处 | +| 展示与通用检索 | render_artifact/search_artifacts;接入通用 search 和 Prepared Context | + +创建知识库、导入、编辑、forget、检索示例: ```json -{"family":"knowledge-base","content":{"title":"Operations SOPs","parser":"markdown-v1","ocr":"rapidocr-local-v1","chunker":{"max_chunk_chars":1200,"overlap_chars":100}}} +{"title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} ``` -导入,目录任务产生有界批次的逐文件子任务,parent_job_id 关联;目录完成只表示枚举/子任务接受结束,不等于全部文件处理成功: - ```json -{"knowledge_base_id":"ops","root":"/work/docs","idempotency_key":"import-01"} +{"root":"/work/docs","paths":["restart.md"],"idempotency_key":"import-01"} ``` -移除 chunk,已有 document 使用当前 If-Match;首次生成使用明确的无 head 前置条件,不猜未来 revision: - ```json -{"knowledge_base_id":"ops","document_id":"doc-1","operation":"remove_chunk","idempotency_key":"edit-03","base_revision":2,"input":{"chunk_id":"chunk-3"}} +{"scope_id":"scope-ops","items":[{"document_id":"doc-1","request_ref":{"source_type":"knowledge-base-process","source_id":"request-01"},"status":"accepted"}]} ``` ```json -{"job_id":"job-03","state":"queued","document_id":"doc-1","target_generation":5} +{"content":{"operation":"edit_chunk","chunk_id":"chunk-1","text":"Check replica health before restarting."}} ``` ```json -{"job_id":"job-03","state":"succeeded","result":{"document_id":"doc-1","revision":3,"kind":"created"}} +{"content":{"operation":"remove_chunk","chunk_id":"chunk-2"}} ``` -精确版本目录和批量读取: - ```json -{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"items":[{"chunk_id":"chunk-1","ordinal":0,"heading_path":["Operations","Restart"],"text_length":128}],"next_cursor":null} +{"revision":3,"state_version":0} ``` ```json -{"chunk_ids":["chunk-1","chunk-2"]} +{"query":"How should I restart a follower?","mode":"hybrid","limit":10} ``` ```json -{"knowledge_base_ids":["ops"],"query":"How should I restart a follower?","mode":"hybrid","limit":10} +{"hits":[{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` -```json -{"hits":[{"knowledge_base_id":"ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"document_file","source_id":"source-1"},"locator":{"heading_path":["Operations","Restart"]}}]} -``` +Chunk API 精确读取指定 revision,不回退当前版本;目录分页不返回正文,单块/批量返回有界正文及出处。Batch-get 拒绝重复 ID、 +缺失 ID 和超限响应,不静默截断;每次先检查 Scope、document 权限和归属。专属存储跨 Scope 共享,不能只凭 chunk ID 读取。 -检索 limit 计 chunk 数;可选 snippet 有界,正文从 chunk 接口获取。通用 Artifact search 继续返回 Artifact,不混入 chunk 响应。 -索引命中必须对应当前 manifest 的 result_id 和索引 profile,并满足归属、权限及删除规则;过滤后继续补取候选,避免无效结果占满 top-k。 -适配覆盖首次写入、版本替换、重建、coverage/摘要核对、零块、删除过滤和命中定位。保留历史正文不要求保留所有历史索引。 -同 profile 重建保留旧可用索引,不能发布缺少所需索引的新内容;模型切换走 8.1 的受控维护流程。 +通用 search 保持框架的 Artifact 引用格式;插件专用 retrieve 提供 chunk 结构。Prepared Context 使用 SearchHit 的片段与 locator, +并遵守字节预算。正常检索先过滤非 active、旧结果及未授权对象,再补取候选;不支持的 filter/rerank 返回明确错误。 +不同 Scope 的查询分别授权,首期不提供聚合接口。Python/HTTP 使用同一业务处理;MCP 与 Dashboard 依框架实际可用能力接入。 -同 Scope 可选择多个知识库;跨 Scope helper 逐个授权显式目标,调用同一分 Scope 接口,融合排名并保留目标身份/错误, -不直接比较不兼容向量空间的原始分数。不支持的 filter/rerank 明确拒绝。Python/MCP 复用同一业务服务。 -权限复用 Scope 读/贡献和 Artifact 写/治理能力,跨对象请求逐个检查。接受失败沿用 428/412 前置条件、409 冲突、410 已删除、 -422 校验、413 大小限制和 503 不可用;202 后的失败记录在任务状态中,不再靠日志推测。 +## 9. 升级、实施与验收 -### 8.1 更换模型并重建索引 +upgrade(ctx) 负责插件表及索引元数据迁移,维护自己的 schema 版本。迁移可重复执行,多实例通过插件库协调;先兼容新旧代码, +历史 Artifact manifest 和旧 Source 定义仍需读取。首期部署可以重启升级,不以热加载实现完成作为知识库首期前提。 +备份必须同时包含 core、插件库和 OpenDAL 快照;core 的备份不自动覆盖插件数据。 -已有数据的活动模型、维度和 embedding 参数不能通过配置 PUT、环境变量刷新或重启直接覆盖。 -只能执行 `switch_model_and_rebuild`;target_profile 固定模型身份/版本、维度、完整 embedding 输入规则和索引配置,密钥仍只保存配置引用。 -由于首期同 Scope 共用 profile,操作需 Scope 管理权限,并确认影响整个 Scope 的知识库;不能声称只修改发起请求的一个知识库。 +框架实现需满足三后端 ctx.storage、单 family writer、同步修改证据、治理并发校验、Source 定义及路由契约; +未落地部分属于现有框架依赖的实现缺口,不另建知识库锁表、读取 guard 或独立队列。必要适配不得绕过 core 公共约束。 -```json -{"knowledge_base_id":"ops","operation":"switch_model_and_rebuild","idempotency_key":"model-switch-01","input":{"expected_profile_id":"embedding-v1","target_profile_id":"embedding-v2","confirm_scope_wide":true}} -``` +在 SQLite、SeekDB、OceanBase 分别验证: -复用 jobs 的 input_snapshot、checkpoint、parent_job_id 和逐文档子任务保存旧/目标 profile、阶段和重建进度,不新增控制表。 -Scope 闸门保证同 Scope 只有一个未完成的切换操作。其持久 checkpoint 阶段为 preparing、rebuilding、publishing、completed、aborted; -失败/进程退出不会自动清除维护状态,不能只用 job 是否 running 判断是否暂停。 -按原切换操作及后继任务链的最新有效 checkpoint 判定维护;后继 completed/aborted 可以关闭该操作,旧 failed 记录保留但不单独继续阻断。 +- 创建 Scope 的管理员权限、配置补写、多 Scope 隔离和固定原文快照。 +- 导入请求各提交边界的重试、同键冲突、内容去重、重复处理及确定失败不阻塞后续文件。 +- 框架窗口回滚/重新投递、失败观察与 core 成功对账;固定 base 冲突不能自动换基准。 +- Markdown、真实 RapidOCR、超长块、完整 embedding 输入预算、原文溯源与人工标记。 +- 同步编辑/移除的 revision 和 lineage_only 证据;零块结果、模型失败及响应丢失。 +- 编辑/forget 与 generate 竞争,不覆盖人工编辑、不恢复 deprecated;原文和历史保留。 +- 准备索引后 core 回滚,旧版本仍可检索;候选过滤、精确 chunk 读取、通用 search 和 Prepared Context。 +- 插件模型指纹不匹配明确失败,Server 主模型变化不改变插件向量空间。 -| 阶段 | 行为 | -| --- | --- | -| 接受/preparing | 持久保存切换任务及旧/目标配置;暂停该 Scope 的检索和普通写入/发布,保留管理状态及精确内容读取;先完成已生效删除的善后 | -| rebuilding | 固定当前有效 document 版本,从已提交 chunks 构建目标 profile 的隔离索引,不重复 OCR;验证数量/摘要、维度和完整输入 token 上限 | -| publishing | 逐文档发布仅更新索引 profile 引用的新 revision,正文 result_id 可复用;写成功操作证据;同步更新所有有效 knowledge-base 的配置 revision | -| completed | 核验全部有效文档、知识库配置与目标索引一致,再在闸门内确认完成并解除维护;查询与后续任务一起使用目标 profile | - -检索/普通写入在维护期明确返回 503 和切换任务引用,不能返回混合模型结果或静默空结果。新建知识库也参与维护检查。 -已生效删除的再次删除/善后不被维护阻断,避免清理失败后无法继续准备切换;新删除请求属于暂停的普通写入。 -切换前的旧 profile 待发布任务不得继续提交:冻结其执行资格并对账,未发布的旧目标标记 superseded,输入不原地改写;需要时由调用者提交新请求。 -查询固定本次 profile,返回前复核维护状态及活动 profile;若期间改变,返回 503,不返回在途旧模型结果。 -精确 chunk/历史读取仍使用固定 result_id,并照常执行删除检查。旧索引至少保留到切换成功。 - -在 preparing/rebuilding 阶段,取消或失败后须在闸门内确认没有 profile revision 发布,再持久记录 aborted 并恢复旧 profile 服务; -不能仅因任务 failed 就解除维护。原来已 superseded 的任务不自动复活。 -一旦开始发布,禁止取消/自动退回旧配置:部分对象可能已切换,必须保持维护并向前补齐。 -调用同一个 switch_model_and_rebuild 操作、相同目标 profile 和新的请求键可创建后继任务,关联原切换操作并跳过已完成 revision, -不复活失败任务、不重复成功证据。相同请求键只返回已有任务;未完成切换期间拒绝不同目标模型。 -若新模型输入预算不足,重建失败并明确要求先调整切块,不静默截断。全程不要求跨数据库原子提交或无停机切换。 - -## 9. 实施与验收 - -仅新增插件存储迁移,已有核心表无需新增字段/迁移。插件框架需提供能力注册、消费准入、受限发布和可见性检查; -“不改表结构”不代表“不需要通用框架适配”。公开路由按主契约/插件 OpenAPI 的归属生成绑定。 - -SQLite、SeekDB、OceanBase 都验证: - -- 同 Scope 多知识库、跨库授权、独占归属、原文排他消费,包括恢复扫描和手动入口。 -- 固定 oceanbase/oceanbase commit 的编译运行、调试和 Wait Event 文档;真实文字图片与 OCR 来源映射。 -- 同请求重放、不同参数冲突、同目标活跃冲突、内容去重、配置重解析和人工编辑保护。 -- 任务接受后退出、Source 已登记但未确认、租约重领、迟到 token、目标替换、有限重试和取消。 -- 结果准备后 core 回滚、core 成功但任务确认失败;旧版本可用、结果不提前可见、不重复发布。 -- 插件连接单独断开、core 连接单独断开、提交响应未知与取消/重领竞争,验证 core Scope 闸门和禁止旧事务重连发布。 -- 创建/修改/删除证据与实际 revision 一致;删除 chunk 版本递增、零块可读、历史保留。 -- Source/document/knowledge-base 删除与发布竞争;墓碑已提交但 head/索引未清理时仍拒绝派生内容读取。 -- 首次导入排队/失败且尚无 Artifact 时删除,知识库级联覆盖未发布资源;与首次发布竞争时不漏删,不虚构删除 revision/证据,资源墓碑提交后不可取消。 -- 删除生效后取消被拒绝,反复删除补齐失败清理,并发重删只产生一个活跃善后 job,已完成对象不重复 revision/证据。 -- 模型配置直接修改被拒绝,Scope 级切换/重建、部分发布后恢复、失败维护和旧 profile 任务失效。 -- Chunk 目录/单块/批量边界、索引全生命周期、重建及有效候选补取。 -- OpenDAL 本地快照对 Server/Worker 可访问,原文件随后变化不改变已接受输入。 - -真实后端和真实 OCR 验收不能由 mock 替代。先用小样本对比两种规则的答案片段召回、SOP 完整性及出处,不宣称已有质量或规模结论。 -#2441 承担接入/资源归属,#2442 承担队列/处理/发布,#2443 承担检索/接口,#2444 承担运行与验收;不新增 Issue。 +固定 oceanbase/oceanbase 文档 commit 做 Markdown 小样本,配合真实文字图片;mock 不能代替真实 OCR 和三后端验收。 +#2441 覆盖接入/配置,#2442 覆盖框架消费/解析/发布,#2443 覆盖检索/编辑接口,#2444 覆盖运行及验收;#2440 总跟踪。 +实现可集中在一个 PR,按模块提交并逐步验收;本文不新增 Issue。 # 缺点 -三张业务表及索引需要插件自己迁移、备份和恢复。独立存储需要发布对账和短提交闸门;完整 chunk 快照、成功操作证据、软删除及终态任务 -都会增加存储。资源表两类记录需要明确约束。首期不提供跨库分布式事务或大规模性能保证,索引重建可能影响同 Scope 的多个知识库。 +复用 Source 窗口意味着基础设施持续失败可能阻塞同 Scope;同步编辑受接口时限约束。插件负责三后端索引、表迁移和备份, +不可变结果与保留历史增加存储。Forget 是退出检索而不是擦除或禁止历史读取;Source 保持不可变且可读。 # 设计理由与替代方案 -- 一个业务插件集中管理归属、任务和配置,内部解析模块仍可独立扩展。 -- 三张插件表在不改核心模型的前提下提供逐 Source 删除和逐文件任务;资源登记合并固定两类记录,避免额外文档状态/回执表。 -- Source 保存不可变内容与成功证据,jobs 保存可变执行状态;不把待执行命令伪装成成功操作 Source。 -- Artifact 管理整篇版本,chunk 明细支持精确读取;直接编辑旧行无法保留历史。 -- 独立队列适合慢解析及外部等待,不依赖原有消费 cursor;只复用 Supervisor 可分离的运行工具。 -- 不可变结果先准备、core 再发布、任务最后确认,尊重插件存储隔离;跨库原子事务不是默认能力。 -- 删除 revision 提供稳定操作证据,head retirement 和读取 guard 控制可见性;仅清除搜索索引不足以删除内容。 +- Scope 对应知识库,与单 family 插件一致,无需知识库 Artifact 或跨 family 写入。 +- 复用 generate 和 cursor,使 Artifact 与消费进度在 core 原子提交;插件只记录接受及处理观察,不重复实现调度。 +- 同步通用 PUT 提供版本校验和成功操作证据;插件 API 写入不自动具有这些证据语义。 +- 原文 Source 与处理请求分开,使重解析不修改原始事实;直接 lineage 和原文溯源的职责明确。 +- 不可变 chunk 结果引用保证历史与失败恢复,不能用覆盖正文的方式实现编辑。 +- Forget 遵循框架生命周期,不增加 Source 墓碑、删除 revision 或全局读取拦截。 # 既有设计 -基于 [插件接口 #2549](https://github.com/oceanbase/powercontext/pull/2549)、[插件 API #2579](https://github.com/oceanbase/powercontext/pull/2579)、 -[Source 身份](1400_source_definition_and_observation_model.md)、[处理监督](1515_artifact_processing_supervisor.md) -和 [Source/Artifact API](1437_source_artifact_rest_api.md)。复用原文身份、Artifact revision、成功操作证据和治理机制, -独立实现知识库任务与 chunk 投影。现有 Atomic Memory retirement 不自动提供 Source 级联删除或插件生命周期检查。 +基于 [插件接口 #2549](https://github.com/oceanbase/powercontext/pull/2549)、 +[插件 API #2579](https://github.com/oceanbase/powercontext/pull/2579)、 +[Source 身份](1400_source_definition_and_observation_model.md)、 +[处理监督](1515_artifact_processing_supervisor.md) 和 [Source/Artifact API](1437_source_artifact_rest_api.md)。 +未来持续采集可接入 [#2617](https://github.com/oceanbase/powercontext/pull/2617),采集 checkpoint 只代表接入进度,不能代表解析完成; +删除采集目标不删除已采集 Source 或 document。 # 待解决问题 -实现前固定复合插件注册/受限 writer 的 core Scope 闸门接口、通用读取 guard 接入和 Source 排他消费准入。 -锁顺序遵循 core Scope、插件资源/job、Artifact head,后端适配需验证连接失效和已有通用写入路径兼容性。 -实现时固定 OCR 模型、切块参数、任务租约/并发/重试限额、API 数量/字节上限及 schema 具体类型。这些不改变本文的数据归属和提交语义。 -恢复/擦除、任务归档幂等保留期、改名身份、逐知识库向量空间与完整编辑文档导出另定契约。 +实现时确定 SQL 类型与索引细节、OCR 模型版本、窗口和文件大小、同步编辑时限、API 字节上限;用真实后端验证框架的 +revision/生命周期竞争行为。三后端存储和 upgrade 等 RFC 能力与实现 PR 的差异需在实施前核对,不将提案当成已发布功能。 +这些实现选择不改变 Source 不删除、forget 不增加 revision、同步编辑、固定请求 base 及独立模型的契约。 # 后续可能性 -增加 Word/PDF/场景图解析器时复用任务、切块、发布和检索流程;外部解析通过保存远端引用并轮询继续,无需首期建设完整解析框架。 -可进一步增加 OpenDAL provider、rerank、邻接/父章节上下文和受限多步检索。扩展效果与成本需要实测,不作为首期前置条件。 +扩展 Word/PDF 解析、持续采集、跨知识库查询、rerank、邻接上下文、运行中撤销及受控模型迁移。 +完整 Source 删除、历史访问撤销、知识库级联删除和独立长任务需要单独确认契约,不作为首期的隐含承诺。 From 1d50a557871471ec14cf617cdc4bfc4529838f1d Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Sun, 15 Nov 2026 14:25:39 +0800 Subject: [PATCH 11/13] docs(rfc): define plugin-local spaces and knowledge base dashboard --- docs/en/rfcs/2570-knowledge-base.md | 171 ++++++++++++++++++++++------ docs/zh/rfcs/2570-knowledge-base.md | 142 ++++++++++++++++++----- 2 files changed, 245 insertions(+), 68 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index 3e3e01478b..1ff11c98e9 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570: Scope-based Knowledge Base document plugin" -description: "One Scope per knowledge base, framework consumption cursors and document Artifacts, with three database backends, synchronous chunk editing and native soft deletion." +description: "Plugin-local space Scopes organize knowledge-base Scopes for cross-base retrieval, a Dashboard, three database backends, synchronous editing and native soft deletion." --- - Proposal Name: `knowledge_base_plugin` @@ -13,12 +13,14 @@ description: "One Scope per knowledge base, framework consumption cursors and do One `knowledge-base` business plugin provides local ingestion, parsing, chunking, versioning, and hybrid retrieval. Each ordinary Scope is one knowledge base. The plugin declares only the `document` family, with one Artifact per complete file. -The knowledge base itself is not an Artifact; plugin storage holds its configuration by scope_id. The plugin supplies original +A plugin-local space Scope groups knowledge-base Scopes. Space identities, membership, and user defaults live only in plugin +storage: core stores neither the space object nor these parent-child relationships. A knowledge base is not an Artifact. The plugin supplies original and processing-request Source definitions and reuses framework generate, Supervisor, and consumption cursors rather than implementing an independent task scheduler. The first phase supports SQLite, SeekDB, OceanBase, Markdown, standalone-image RapidOCR, rule-based chunking, synchronous -chunk edits/removals, and document forget. This is a target design dependent on framework contracts, not a claim that the +chunk edits/removals, document forget, a Dashboard, browser uploads, and cross-base retrieval within a space. Spaces organize +query scope; they do not introduce tenant isolation or team authorization. This is a target design dependent on framework contracts, not a claim that the current implementation PR provides every capability. # Motivation @@ -29,18 +31,20 @@ holds bodies and indexes. Existing scheduling, revision preconditions, and lifec # Guide-level explanation -1. An administrator creates a knowledge-base Scope and saves parsing/chunking configuration, then imports local files or a - directory accessible to the Server. -2. The plugin saves immutable snapshots, registers Sources, and submits processing-request Sources. Acceptance is not parsing success. -3. Framework generate asynchronously processes Markdown/images, prepares complete chunks and indexes, then publishes a document. -4. Changed content and explicit reprocessing retain the document ID. Failures preserve existing revisions. Status distinguishes +1. Select a plugin-local space, defaulting to the caller's own default space. An administrator creates a knowledge-base Scope + in that space and saves parsing/chunking configuration. +2. Upload files through the Dashboard or import a Server-readable directory; select multiple knowledge bases within the space for retrieval. +3. The plugin saves immutable snapshots, registers Sources, and submits processing-request Sources. Acceptance is not parsing success. +4. Framework generate asynchronously processes Markdown/images, prepares complete chunks and indexes, then publishes a document. +5. Changed content and explicit reprocessing retain the document ID. Failures preserve existing revisions. Status distinguishes pending, latest failure, published, and conflict/skipped. -5. Synchronous chunk edits/removals increment the document revision; core records a lineage_only success Source in the same transaction. -6. Whole-document soft deletion uses generic forget: deprecated, excluded from normal retrieval, with no new revision. Bodies, +6. Synchronous chunk edits/removals increment the document revision; core records a lineage_only success Source in the same transaction. +7. Whole-document soft deletion uses generic forget: deprecated, excluded from normal retrieval, with no new revision. Bodies, originals, and history remain stored. The first phase does not promise in-flight cancellation, Source deletion, knowledge-base cascades, physical erasure, an -independent queue, online model switching, cross-base aggregate retrieval, continuous directory sync, or remote runners. +independent queue, online model switching, cross-space aggregation, generated answers, nested/movable/deletable spaces, team +membership or permission inheritance, continuous directory sync, or remote runners. PDF/Office, scene-image understanding, OCR of embedded Markdown images, semantic/LLM chunking, and large-corpus benchmarks are out of scope. Restore/merge methods are not implemented initially; generic routes report unsupported. Import is not restoration. @@ -49,14 +53,16 @@ are out of scope. Restore/merge methods are not implemented initially; generic r ## 1. Plugin, Scope, and framework dependencies Follow [#2549](https://github.com/oceanbase/powercontext/pull/2549) for single-family plugins, Source definitions, writers, -models, and storage, and [#2579](https://github.com/oceanbase/powercontext/pull/2579) for routes, Scope management, and upgrades. -[#2616](https://github.com/oceanbase/powercontext/pull/2616) is an implementation dependency; capabilities such as dedicated -storage on all three backends require actual implementation and validation. [#2617](https://github.com/oceanbase/powercontext/pull/2617) +models, and storage, and [#2579](https://github.com/oceanbase/powercontext/pull/2579) for routes and Scope management. +Use public master capabilities as the implementation baseline. Dedicated three-backend storage, original edit-payload evidence, +and Dashboard forwarding of generic operations need limited framework adaptation. Initialize through setup without depending +on a framework upgrade hook. [#2617](https://github.com/oceanbase/powercontext/pull/2617) is a future collection integration, not a prerequisite for explicit local imports. | Object | Model | | --- | --- | -| Knowledge base | Ordinary Scope; scope_id is its identity | +| Space Scope | Plugin-local logical Scope, space_scope_id; no core Scope record | +| Knowledge-base Scope | Ordinary core Scope, scope_id; belongs to exactly one space initially | | Plugin | knowledge-base, one installed directory, one document family | | Original | knowledge-base-file Source, pinned snapshot and original path | | Processing request | knowledge-base-process Source, pinned original reference, configuration, base, and request identity | @@ -65,7 +71,9 @@ is a future collection integration, not a prerequisite for explicit local import ```mermaid flowchart TD - S[Scope: knowledge base] --> C[Plugin configuration] + P[Plugin-local space Scope] --> M[Plugin-only membership] + M --> S[Core Scope: knowledge base] + S --> C[Plugin configuration] S --> O[Original Source and immutable snapshot] O --> R[Processing request Source] R --> G[Framework generate and cursor] @@ -85,6 +93,29 @@ Plugin inputs subscribe only to processing requests, so originals do not indepen reserves knowledge-base Scopes for this use and does not enable other content consumers. A Source type name is not framework enforced exclusive admission; isolation from arbitrary other consumers is not a guarantee of this plugin. +### 1.1 Space Scopes and default selection + +space_scope_id and core scope_id are separate namespaces. Never pass a space ID to core Scope APIs. The UI calls it a space; +Workspace may be a display label, not another Artifact family or core domain model. Initially spaces are one level deep and +one knowledge base has one parent. Store membership as indexed space_scope_id on the plugin's scope configuration row, never +as core parent_scope_id or context_references. + +Defaults use the authenticated ctx.caller.principal_id. First default resolution idempotently creates a personal space and +its default mapping; concurrent callers resolve the same space. This creates no core Scope or contribution grant. Users may +select a visible space as their default. A space records a personal owner or team kind; team is an organizational label only. +Explicit space creation/renaming and knowledge-base creation/renaming require server.admin. Implicit personal-space registration +and changing one's own default do not require permission to create core Scopes. + +Personal owners can see their spaces; a caller who can read a contained knowledge base can see its space; administrators can +manage empty spaces. Lists/counts include only readable knowledge bases. Membership grants no Scope read/contribute or Artifact +write, permission inheritance, tenant isolation, or cascade deletion. An inaccessible default returns an error requiring a new +selection; a space without readable bases returns no hits, never a global fallback. Moving knowledge bases or deleting spaces +is not supported initially, avoiding implicit data migrations. + +Creating a knowledge base resolves its space, idempotently creates the core Scope, then commits membership/configuration in +plugin storage before reporting readiness. A creation key cannot rebind to another space. Retry incomplete registration using +the same key; a Scope missing membership/configuration cannot receive imports or enter space queries. + ## 2. Local storage, identity, and request acceptance OpenDAL fs manages snapshot directories accessible to the importer, Server, and Workers. Original paths are provenance; @@ -99,8 +130,13 @@ request_key = (scope_id, idempotency_key) result_id = digest(canonical complete chunk result and provenance) ``` -Collection derives from the storage alias and normalized root, not a scan batch. Compare full identities on hash matches. -The same file in different Scopes is independent. Same path/bytes reuse the original Source; changed bytes create a new Source +For Server directories, collection derives from the storage alias and normalized root. Browser uploads use a stable collection +within the knowledge base, never a new collection per batch. Browsers provide filenames/relative paths, not trusted client +absolute paths. Record origin_kind, collection, and relative_path; OpenDAL fs saves uploaded bytes in the shared Server-local +snapshot directory. Equal names from the two origin types are independent by default; the same collection/path retains identity. +Use bounded binary requests and request keys, normalize relative paths, reject traversal, and keep file bodies out of JSON Sources. +Compare full identities on hash matches. Files in different knowledge-base Scopes remain independent; space IDs are not part of +file_key. Same path/bytes reuse the original Source; changed bytes create a new Source but retain the document ID. Renames are new files; disappearance does not automatically forget a document. Each processing request pins original_source_ref, snapshot_ref, processing settings, independent model fingerprint, @@ -147,9 +183,16 @@ without changing existing core schemas. Originals stay in local OpenDAL director | Plugin domain table | Fields and constraints | | --- | --- | -| pc_knowledge_base_resources | Primary key (scope_id, resource_kind, resource_key); fixed scope/document/request kinds; bounded payload, request_digest, source_ref, document_id, latest processing observations and timestamps | +| pc_knowledge_base_spaces | Primary key space_scope_id; title, kind, personal_owner_id, created_by, creation_key, request_digest, version; unique personal owner and creation key | +| pc_knowledge_base_space_defaults | Primary key principal_id; space_scope_id, version; one default mapping per authenticated user | +| pc_knowledge_base_resources | Primary key (scope_id, resource_kind, resource_key); fixed scope/document/request kinds; one scope configuration row with indexed space_scope_id; bounded payload, request_digest, source_ref, document_id, latest observations and timestamps | | pc_knowledge_base_chunks | Primary key (scope_id, document_id, result_id, chunk_id); ordinal unique within a result; text, text_length, content_digest, heading_path, source_locator, origin, edit_metadata | +There are four plugin domain tables; spaces/defaults do not invent core scope_id values. Validate space references in plugin +transactions, use version preconditions for default updates, and atomically initialize a personal space/default without replacing +an existing default. Explicit space-creation keys are scoped to their creator; changed parameters conflict. Reuse the scope +resource row for membership without an additional relationship table or core schema changes. + Resources is a fixed-purpose register, not a generic task framework: scope rows hold configuration/version, document rows stable file identities, and request rows immutable accepted inputs, receipts, and latest attempt observations. No leases, execution tokens, claiming queue, or cleanup cursors; do not copy the Artifact publication pointer or lifecycle. Request results may refer @@ -183,7 +226,8 @@ bounded file sizes to keep OCR/model windows within limits; arbitrary files are | Core publication completed | Derive published state and exact revision from manifest/history applied_request_ref | | Core succeeded but plugin status acknowledgement failed | Reconcile core, not failure or duplicate publication inferred from a missing status | -Failure observations describe the latest attempt, not proof of cursor acknowledgement. Plugin status cannot advance consumption +Display the currently usable revision separately from the latest request status: failed reprocessing does not make an older +committed revision unusable. Failure observations describe the latest attempt, not proof of cursor acknowledgement. Plugin status cannot advance consumption or justify skipping unproven core writes. Persistent infrastructure failure may block subsequent windows in the Scope; independent unlimited per-file concurrency and a dead-letter queue are not promised. User retries of deterministic failures use new requests; old Sources remain unchanged. Processing requests express intent, not lineage_only success. @@ -244,8 +288,13 @@ default successful JSON responses may use 200. | Operation | API and response | | --- | --- | -| Create knowledge base | POST `P/knowledge-bases`, ctx.scopes.create plus configuration; returns scope_id | +| List/create/rename spaces | GET/POST `P/spaces`, PATCH `P/spaces/{space_scope_id}`; plugin-local spaces, writes require idempotency keys or version preconditions | +| My default space | GET/PUT `P/me/default-space`; current caller's space_scope_id and version; no caller-supplied principal_id for other users | +| List/create knowledge bases | GET/POST `P/knowledge-bases`; optional space_scope_id, otherwise resolve default; create core Scope and save membership/configuration, returning both IDs | +| Rename/configure knowledge base | PATCH `P/scopes/{s}/settings`; ctx.scopes.update for title/summary, plugin storage for chunking, separate version preconditions | | Import files | POST `P/scopes/{s}/imports`, bounded paths and idempotency_key; per-file request SourceRefs | +| Browser upload | POST `P/scopes/{s}/uploads`, binary body; collection, relative_path, idempotency_key in query; same acceptance path | +| Document list | GET `P/scopes/{s}/documents`, paginated published summaries and unpublished request observations; core determines revision/lifecycle | | Reprocess/retry | POST `P/scopes/{s}/documents/{d}/reprocess`, base, pinned configuration, original reference, new request key | | Processing status | GET `P/scopes/{s}/imports/{request_id}`, acceptance, latest attempt, and verifiable publication | | Document overview/history | Generic Artifact GET/revisions, bounded manifest | @@ -254,12 +303,13 @@ default successful JSON responses may use 200. | Chunk directory/body | GET `P/scopes/{s}/documents/{d}/revisions/{rev}/chunks`; append `/{chunk_id}` for body | | Batch chunks | POST directory path plus `/batch-get`, bounded chunk_ids | | Chunk hybrid retrieval | POST `P/scopes/{s}/retrieve`, exact revision, chunk ID, score, provenance | +| Cross-base retrieval within a space | POST `P/retrieve`, optional space_scope_id/scope_ids; resolve as below, hits carry space and knowledge-base IDs | | Rendering/generic search | render_artifact/search_artifacts; generic search and Prepared Context integration | Examples for knowledge-base creation, import, editing, forget, and retrieval: ```json -{"title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} +{"space_scope_id":"space-team","title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} ``` ```json @@ -287,7 +337,7 @@ Examples for knowledge-base creation, import, editing, forget, and retrieval: ``` ```json -{"hits":[{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} +{"hits":[{"space_scope_id":"space-team","scope_id":"scope-ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` Chunk APIs read the requested exact revision without current-version fallback. Directory pagination omits bodies; single/batch @@ -296,23 +346,69 @@ Check Scope/document permissions and ownership first; plugin storage spans Scope Generic search retains the framework's Artifact-reference response; plugin retrieve returns chunk structures. Prepared Context uses SearchHit text/locators within its byte budget. Normal search excludes non-active, stale, and unauthorized candidates before -refilling. Unsupported filter/rerank parameters fail explicitly. Different Scopes are authorized separately; no aggregate API -initially. Python/HTTP share business handling; MCP and Dashboard integration follows actually available framework capabilities. +refilling. Unsupported filter/rerank parameters fail explicitly. Python/HTTP share business semantics. Generic search/Prepared +Context retain their Scope contract; plugin retrieve provides space aggregation. + +### 8.1 Space selection and cross-base retrieval + +1. Omitted space_scope_id resolves the caller's default; an explicit value must be visible. Every explicit scope_id must belong + to that space; selecting bases never implicitly switches the resolved space. +2. Omitted scope_ids selects readable bases in that space; an explicit empty list selects none. An explicitly inaccessible or + out-of-space base fails the whole request rather than being silently omitted. Bound base count, request size, and total hits; + require complete defaults/membership/configuration and never broaden to global search. +3. Retrieve full-text/vector candidates in the selected range and fuse them consistently. Reuse the query vector for the fixed + embedding profile. Use comparable scoring/common candidate ranking, not raw BM25 scores from separate per-base corpora. + Constrain candidates by Scope, then verify core access, active lifecycle, current result_id/profile, and refill after filtering. +4. Hits carry space_scope_id, scope_id, document_ref including revision, chunk_id, score, and provenance. Deduplicate with full + ownership/result identity; importing the same file into different bases does not merge its evidence. Exact chunk reads still + resolve by knowledge-base Scope and revision. + +```json +{"space_scope_id":"space-team","scope_ids":["scope-ops","scope-dev"],"query":"How should I restart after a release?","mode":"hybrid","limit":10} +``` + +A query alone searches readable bases in the default space; space_scope_id alone selects readable bases in that space. +Aggregation reuses single-base authorization, lifecycle, and revision rules without nested HTTP requests. Backend failures are +explicit; partial success and a consistent snapshot across bases are not first-phase promises. + +## 9. Dashboard + +PluginPages provides space/default selection, knowledge-base management, Markdown/standalone-image drag-and-drop upload and +local-directory import, document/request status, retry/reprocess, paginated chunk metadata/bodies, history viewing, synchronous +edit/removal, document forget, and multi-base retrieval within a space. Filter lists by permissions and retain operation-specific +access checks: creation/configuration management requires server.admin, imports require scope.contribute, and edit/forget retain +artifact.write. Resolve valid chunking configuration before initial import; no separate post-upload pending-configuration queue. + +Display the usable revision separately from the latest request. A failure does not hide previously committed content. Successful +edits show the new revision; conflicts require re-reading, and uncertain responses require reconciliation. Removing the final +chunk is valid. Label forget as removal from retrieval with history retained; omit cancellation, restoration, whole-base deletion, +and generated-answer controls. + +The sandboxed iframe calls declared plugin routes through the framework client; reads can wrap ctx.reads. Generic document +PUT/forget requires limited framework forwarding: allow only declared operations on the owning plugin's family, retain the +current caller's authorization, forward If-Match/revision/state_version, and validate knowledge-base ownership. Do not provide +arbitrary URL forwarding or session credentials. Invoke the generic Artifact operation and its atomic evidence path; an ordinary +plugin writer or asynchronous edit Source is not a substitute. Upload files separately within binary request limits, enforce +server-side path/size bounds, and do not present uploaded-file counts as completed parsing progress. -## 9. Upgrade, implementation, and acceptance +## 10. Initialization, implementation, and acceptance -upgrade(ctx) manages plugin schema/index metadata migrations and a plugin-owned schema version. Upgrades are repeatable and -coordinate in plugin storage across instances. Keep changes compatible with overlapping code versions and retain historical -manifest/Source decoding. Initial deployments may restart for upgrades; completed hot reload is not a knowledge-base prerequisite. +setup invokes plugin-owned idempotent initialization and schema-version checks. Deployment runs plugin migrations with +coordination in plugin storage across instances. Preserve historical manifest/Source decoding and reject incompatible versions. +The first phase restarts for deployment and does not depend on an upgrade(ctx) hook or hot reload. Backups must include core, plugin storage, and OpenDAL snapshots; core backups do not automatically cover plugin data. Framework implementation must supply three-backend ctx.storage, single-family writers, synchronous modification evidence, -governance concurrency checks, Source definitions, and routes. Missing RFC features are implementation dependencies, not grounds -for additional knowledge-base lock tables, read guards, or an independent queue. Necessary adapters must preserve core contracts. +governance concurrency checks, Source definitions, and routes. Explicit adaptations are three-backend ctx.storage, evidence +preserving the original caller payload rather than the generated manifest, and restricted Dashboard generic-operation forwarding. +Do not introduce knowledge-base lock tables, read guards, or an independent queue; adapters must preserve core contracts. Validate on SQLite, SeekDB, and OceanBase: -- Administrator-only Scope creation, configuration retry, multi-Scope isolation, immutable snapshots. +- Concurrent plugin-local space/default initialization, default-update conflicts, unique membership, no core space hierarchy. +- Default/explicit space queries, empty selections, inaccessible/out-of-space rejection, filtered counts, global top-k, scoped citations. +- Sandboxed Dashboard generic-operation forwarding, preserved If-Match, zero-chunk edits, separate statuses and usable old revisions. +- Administrator-only Scope creation, membership/configuration retry, multi-Scope isolation, snapshots, stable identities/path bounds for both origins. - Retries across import acceptance boundaries, key conflicts, content deduplication, repeated handling, and deterministic failures that do not block later files. - Window rollback/redelivery, failure observations versus committed core success, and pinned-base conflicts without automatic rebasing. @@ -323,8 +419,8 @@ Validate on SQLite, SeekDB, and OceanBase: - Explicit model-fingerprint mismatch failures; Server model changes do not alter the plugin vector space. Use Markdown from a pinned oceanbase/oceanbase commit and real text images. Mocks cannot establish real OCR or backend support. -#2441 covers ingestion/configuration; #2442 framework consumption/parsing/publication; #2443 retrieval/edit APIs; #2444 operation -and acceptance; #2440 tracks the whole feature. Implementation may use one PR with staged commits and validation. No new issues. +#2441 covers spaces/defaults/ingestion/configuration; #2442 framework consumption/parsing/publication; #2443 cross-base retrieval, +editing, and Dashboard; #2444 operation/acceptance; #2440 tracks the whole feature. Implementation may use one PR with staged commits and validation. No new issues. # Drawbacks @@ -334,7 +430,8 @@ not history access or stored evidence; Sources remain immutable and readable. # Rationale and alternatives -- Scope is the knowledge base, matching a single-family plugin without another Artifact or cross-family writes. +- Plugin-local space Scopes organize knowledge-base Scopes; membership/defaults stay in plugin tables without core hierarchy or implied grants. +- A core Scope is a knowledge base, matching a single-family plugin without another Artifact or cross-family writes. - Framework generate/cursor atomically commits Artifacts and consumption progress; the plugin records acceptance/observations rather than duplicating scheduling. - Generic synchronous PUT supplies preconditions and success evidence; plugin-route writes do not automatically have those semantics. @@ -355,11 +452,11 @@ acceptance, not completed parsing; deleting a collection target does not delete Implementation fixes SQL/index details, OCR model versions, window/file sizes, synchronous editing limits, and API byte bounds. Validate revision/lifecycle races on real backends. Check gaps between framework RFCs and implementations, including dedicated -storage and upgrades; proposals are not released capabilities. These choices do not change append-only Sources, forget without +storage, edit evidence, and Dashboard forwarding; proposals are not released capabilities. These choices do not change append-only Sources, forget without new revisions, synchronous edits, pinned request bases, or independent models. # Future possibilities -Word/PDF parsing, continuous collection, cross-base queries, rerank, adjacent context, in-flight cancellation, and controlled model +Word/PDF parsing, continuous collection, cross-space queries, generated answers, rerank, adjacent context, in-flight cancellation, and controlled model migration. Complete Source deletion, revoking historical access, knowledge-base cascades, and independent long tasks require separate contracts rather than implicit first-phase promises. diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index 3e27dbee16..a943142e28 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -1,6 +1,6 @@ --- title: "RFC 2570:基于 Scope 的 Knowledge Base 文档插件" -description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 document Artifact,支持三种数据库、同步 chunk 编辑及框架原生软删除。" +description: "插件内空间 Scope 组织知识库 Scope,支持空间内跨库检索、Dashboard、三种数据库、同步 chunk 编辑及原生软删除。" --- - Proposal Name: `knowledge_base_plugin` @@ -12,10 +12,12 @@ description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 # 概述 一个 `knowledge-base` 业务插件提供本地文档接入、解析、切块、版本管理及混合检索。一个普通 Scope 对应一个知识库, -插件只声明 `document` family,每个 Artifact 表示整篇文档。知识库本身不是 Artifact;业务配置按 scope_id 保存于插件存储。 +插件只声明 `document` family,每个 Artifact 表示整篇文档。插件内的空间 Scope 组织多个知识库 Scope;空间身份、父子关系及 +用户默认空间仅存在插件表中,不向 core 创建空间记录或写入 Scope 父子关系。知识库本身不是 Artifact。 插件附带原文和处理请求 Source 定义,后台复用框架 generate、Supervisor 和消费 cursor,不实现独立任务调度队列。 -首期支持 SQLite、SeekDB、OceanBase,Markdown、独立图片 RapidOCR、规则切块、同步 chunk 编辑/移除和文档 forget。 +首期支持 SQLite、SeekDB、OceanBase,Markdown、独立图片 RapidOCR、规则切块、同步 chunk 编辑/移除、文档 forget、 +Dashboard、浏览器上传和空间内跨知识库检索。空间是组织与查询范围,不是另建租户或团队权限系统。 这是依赖框架契约的目标设计,不表示当前实现 PR 已提供全部能力。 # 动机 @@ -25,15 +27,17 @@ description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 # 使用层说明 -1. 管理员创建知识库 Scope,并保存解析/切块配置,然后导入 Server 可访问的本地目录或文件。 -2. 插件保存不可变原文快照、登记 Source,并提交处理请求 Source;导入接受不等于解析完成。 -3. 框架异步调用 generate,处理 Markdown/图片,准备完整 chunks 和索引,再发布 document。 -4. 内容变化或显式重解析沿用 document ID;失败保留已有版本。状态区分待处理、最近失败、已发布及冲突/跳过。 -5. 用户同步编辑或移除 chunk,document revision 增加,core 在同一事务记录 lineage_only 成功操作 Source。 -6. 文档软删除使用通用 forget:变为 deprecated、退出正常检索,不增加 revision。正文、原文和历史保留。 - -首期不承诺运行中撤销,不提供 Source 删除、知识库级联删除、物理擦除、独立任务队列、在线换模型、跨知识库聚合检索、 -持续目录同步或远端 runner。PDF/Office、复杂场景图、Markdown 内嵌图片 OCR、语义/LLM 切块和几万篇规模评测不在首期。 +1. 用户选择插件内空间,未指定则使用自己的默认空间。管理员在空间中创建知识库 Scope,并保存解析/切块配置。 +2. 用户通过 Dashboard 上传文件,或导入 Server 可访问的本地目录;可在空间内选择多个知识库联合检索。 +3. 插件保存不可变原文快照、登记 Source,并提交处理请求 Source;导入接受不等于解析完成。 +4. 框架异步调用 generate,处理 Markdown/图片,准备完整 chunks 和索引,再发布 document。 +5. 内容变化或显式重解析沿用 document ID;失败保留已有版本。状态区分待处理、最近失败、已发布及冲突/跳过。 +6. 用户同步编辑或移除 chunk,document revision 增加,core 在同一事务记录 lineage_only 成功操作 Source。 +7. 文档软删除使用通用 forget:变为 deprecated、退出正常检索,不增加 revision。正文、原文和历史保留。 + +首期不承诺运行中撤销,不提供 Source 删除、知识库级联删除、物理擦除、独立任务队列、在线换模型、 +跨空间聚合、生成式问答、空间嵌套/迁移/删除、团队成员或权限继承、持续目录同步或远端 runner。PDF/Office、复杂场景图、 +Markdown 内嵌图片 OCR、语义/LLM 切块和几万篇规模评测不在首期。 恢复/合并方法首期不实现,对应通用入口按框架返回不支持;不能把导入当作恢复操作。 # 参考层说明 @@ -41,13 +45,15 @@ description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 ## 1. 插件、Scope 与框架依赖 遵循 [#2549](https://github.com/oceanbase/powercontext/pull/2549) 的单 family、Source 定义、writer、模型和存储契约, -以及 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 的插件路由、Scope 管理和 upgrade 契约。 -[#2616](https://github.com/oceanbase/powercontext/pull/2616) 是实现依赖;其三后端专属存储等能力需要实际落地验证。 +以及 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 的插件路由和 Scope 管理方向。 +以 master 的公开能力为实现基线;三后端专属存储、原始编辑载荷证据及 Dashboard 通用操作转发需要必要的框架适配。 +初始化使用 setup,首期不依赖框架提供 upgrade 钩子。 [#2617](https://github.com/oceanbase/powercontext/pull/2617) 仅是后续持续采集的接入方向,不是本地显式导入的前置条件。 | 对象 | 模型 | | --- | --- | -| 知识库 | 普通 Scope,scope_id 是知识库身份 | +| 空间 Scope | 插件内逻辑 Scope,space_scope_id;无 core Scope 记录 | +| 知识库 Scope | 普通 core Scope,scope_id;首期唯一归属于一个空间 | | 插件 | knowledge-base,单个安装目录,单个 document family | | 原文 | knowledge-base-file Source,固定快照及原路径 | | 处理请求 | knowledge-base-process Source,固定原文引用、配置、base 和请求身份 | @@ -56,7 +62,9 @@ description: "一个 Scope 对应一个知识库,复用插件消费 cursor 和 ```mermaid flowchart TD - S[Scope: knowledge base] --> C[Plugin configuration] + P[Plugin-local space Scope] --> M[Plugin-only membership] + M --> S[Core Scope: knowledge base] + S --> C[Plugin configuration] S --> O[Original Source and immutable snapshot] O --> R[Processing request Source] R --> G[Framework generate and cursor] @@ -73,6 +81,23 @@ flowchart TD 插件 inputs 只订阅处理请求 Source,原文不会重复触发本插件生成。知识库 Scope 按部署约定专用,不启用其他内容消费者; 不宣称 Source 类型名称提供框架级排他隔离,其他消费者的准入能力不属于本插件的保证。 +### 1.1 空间 Scope 与默认范围 + +space_scope_id 和 core scope_id 是不同命名空间,接口必须区分,不能把空间 ID 传给 core Scope API。界面称“空间”, +Workspace 可以是英文展示词,不是新增 Artifact family 或另一套 core 领域模型。首期仅一级空间、每库一个归属。 +知识库与空间的归属保存到插件 scope 配置行,带索引的 space_scope_id 不写入 core parent_scope_id 或 context_references。 + +插件按已认证的 ctx.caller.principal_id 保存默认空间。首次解析默认空间时,幂等创建个人空间及默认映射;并发请求返回同一空间, +这不创建 core Scope 或授予贡献权限。用户可以把自己可见的空间设为默认。空间记录个人所有者或团队类型,团队类型仅是组织标签。 +显式空间创建/改名、知识库创建/改名沿用 server.admin;个人默认空间的自动登记与修改自己的默认映射不需要创建 core Scope 的权限。 + +个人空间对所有者可见;有权读取其中知识库的用户可看到包含它的空间;管理员可以管理空空间。列表和计数仅包含调用者可读的知识库。 +归属不授予 Scope read/contribute 或 Artifact write,也不产生权限继承、租户隔离和级联删除。默认空间失去可见性时返回错误并要求 +重新选择;没有可读知识库时返回空结果,不回退全局搜索。首期不支持变更知识库所属空间或删除空间,避免隐含跨库数据迁移。 + +创建知识库时先解析空间,随后幂等创建 core Scope,并在插件事务内保存唯一归属和配置;全部完成后才报告可用。 +相同创建键不得改绑到其他空间。core 创建成功而插件事务失败时,同键补齐;归属/配置不完整的 Scope 不参与空间查询,也不可导入。 + ## 2. 本地存储、身份与请求接受 OpenDAL fs 管理 Server、导入进程和 Worker 均可访问的本地快照目录。原路径只作出处,解析只读快照。 @@ -86,7 +111,11 @@ request_key = (scope_id, idempotency_key) result_id = digest(canonical complete chunk result and provenance) ``` -Collection 从存储别名和规范化根目录派生,不取自扫描批次;保存完整身份以检查 hash 碰撞。同文件跨 Scope 是独立逻辑文档。 +Server 目录的 collection 从存储别名和规范化根目录派生;浏览器上传使用知识库内稳定的上传 collection,不能按批次重新生成。 +浏览器提交文件名或相对路径,不声称掌握客户端绝对路径。记录 origin_kind、collection 和 relative_path,上传字节仍由 OpenDAL fs +落到共享可访问的 Server 本地快照目录。两种来源的同名文件默认独立;同一 collection 同相对路径沿用相同逻辑文件身份。 +上传使用有界二进制请求及请求键,归一化相对路径并拒绝越界;不将文件正文放入 JSON Source。保存完整身份以检查 hash 碰撞。 +同文件跨知识库 Scope 是独立逻辑文档;空间 ID 不进入 file_key,实际数据归属仍是知识库。 同路径同字节复用原文 Source;变化产生新原文 Source,但 document ID 不变。改名视作新文件,文件消失不自动 forget。 每次处理请求固定 original_source_ref、snapshot_ref、处理配置、独立模型指纹、base_revision、manual_edits_policy 及请求摘要。 @@ -123,9 +152,15 @@ ctx.storage 使用与 Server 相同的后端:SQLite 为独立文件,SeekDB | 插件业务表 | 字段及约束 | | --- | --- | -| pc_knowledge_base_resources | 主键 (scope_id, resource_kind, resource_key);固定三类 scope/document/request;有界 payload、request_digest、source_ref、document_id、最近处理观察及时间 | +| pc_knowledge_base_spaces | 主键 space_scope_id;title、kind、personal_owner_id、created_by、creation_key、request_digest、version;个人所有者及创建键唯一 | +| pc_knowledge_base_space_defaults | 主键 principal_id;space_scope_id、version;每个已认证用户一个默认映射 | +| pc_knowledge_base_resources | 主键 (scope_id, resource_kind, resource_key);固定 scope/document/request;scope 配置行唯一并带 space_scope_id 索引;有界 payload、request_digest、source_ref、document_id、最近处理观察及时间 | | pc_knowledge_base_chunks | 主键 (scope_id, document_id, result_id, chunk_id);ordinal 同结果唯一;text、text_length、content_digest、heading_path、source_locator、origin、edit_metadata | +共四张插件业务表;空间与默认映射不伪造 core scope_id。空间引用在插件事务内验证;默认更新使用版本前置条件,个人空间/默认映射 +首次创建在一个插件事务内完成;已有默认映射不被初始化覆盖。显式空间创建键按创建者限定,同键不同参数冲突。 +知识库归属复用 resources 的 scope 行,不再增加关系表;不修改核心表。 + Resources 是固定用途登记,不是通用任务框架:scope 行保存配置/版本;document 行保存稳定文件身份;request 行保存不可变接受参数、 幂等回执及最近尝试结果。它没有租约、执行 token、领取队列或清理 cursor,也不复制 Artifact 的发布指针与生命周期。 请求结果可以引用精确 revision 供对账,成功事实仍以 core 为准。全文/向量辅助结构属于派生索引,不计入业务表数。 @@ -153,6 +188,7 @@ Document content 只保存标题、原文 SourceRef、文件身份、result_id | core 发布完成 | 从 manifest/历史中的 applied_request_ref 判定已发布及精确 revision | | 发布成功但插件状态未更新 | 根据 core 对账,不能仅凭缺少状态把它判为失败或重复发布 | +文档当前可用 revision 与最新处理请求状态独立展示:重解析失败不会把旧有效版本改成不可用。 资源表的失败是最近尝试观察,不等于 cursor 已确认;不能仅凭插件状态推进消费或跳过尚未证明完成的 core 写入。 基础设施持续故障可能阻塞该 Scope 的后续窗口,这是复用框架的边界,不承诺独立逐文件无限制并发或死信队列。 确定输入失败的人工重试使用新请求;旧 Source 不修改。处理请求是意图,不是 lineage_only 成功证据。 @@ -200,8 +236,13 @@ Content Source,document revision 增加。修改保留逻辑 chunk ID 和原 | 操作 | 接口和返回 | | --- | --- | -| 创建知识库 | POST `P/knowledge-bases`,调用 ctx.scopes.create 并保存配置;返回 scope_id | +| 空间列表/创建/改名 | GET/POST `P/spaces`、PATCH `P/spaces/{space_scope_id}`;插件内逻辑空间,写入带幂等键或版本前置条件 | +| 我的默认空间 | GET/PUT `P/me/default-space`;当前用户的 space_scope_id 和 version,不接受替他人设置的 principal_id | +| 知识库列表/创建 | GET/POST `P/knowledge-bases`,可指定 space_scope_id,否则解析默认空间;创建 core Scope 并保存归属/配置,返回两类 ID | +| 知识库改名/配置 | PATCH `P/scopes/{s}/settings`;名称/摘要复用 ctx.scopes.update,切块配置存插件;分别使用版本前置条件 | | 导入文件 | POST `P/scopes/{s}/imports`,有界 paths、idempotency_key;返回逐文件请求 SourceRef | +| 浏览器上传 | POST `P/scopes/{s}/uploads`,二进制正文,query 携带 collection、relative_path、idempotency_key;复用同一接受流程 | +| 文档列表 | GET `P/scopes/{s}/documents`,分页合并已发布概览和未发布请求观察;从 core 核实 revision/生命周期 | | 重解析/重试 | POST `P/scopes/{s}/documents/{d}/reprocess`,base、固定配置、原文引用、新请求键 | | 处理状态 | GET `P/scopes/{s}/imports/{request_id}`,接受记录、最近尝试及可核实的发布结果 | | 文档概览/历史 | 通用 Artifact GET/revisions,返回有界 manifest | @@ -210,12 +251,13 @@ Content Source,document revision 增加。修改保留逻辑 chunk ID 和原 | chunk 目录/正文 | GET `P/scopes/{s}/documents/{d}/revisions/{rev}/chunks`,追加 `/{chunk_id}` 获取正文 | | 批量 chunk | POST 上述目录路径追加 `/batch-get`,有界 chunk_ids | | chunk 混合检索 | POST `P/scopes/{s}/retrieve`,返回精确 revision、chunk ID、分数及出处 | +| 空间内跨库检索 | POST `P/retrieve`,space_scope_id、scope_ids 均可省略;按下文解析范围,返回带空间和知识库 ID 的命中 | | 展示与通用检索 | render_artifact/search_artifacts;接入通用 search 和 Prepared Context | 创建知识库、导入、编辑、forget、检索示例: ```json -{"title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} +{"space_scope_id":"space-team","title":"Operations SOPs","summary":"Runbooks","idempotency_key":"kb-01","chunker":{"max_chunk_chars":1200,"overlap_chars":100}} ``` ```json @@ -243,7 +285,7 @@ Content Source,document revision 增加。修改保留逻辑 chunk ID 和原 ``` ```json -{"hits":[{"document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} +{"hits":[{"space_scope_id":"space-team","scope_id":"scope-ops","document_ref":{"family":"document","artifact_id":"doc-1","revision":3},"chunk_id":"chunk-1","score":0.82,"source_ref":{"source_type":"knowledge-base-file","source_id":"original-1"},"locator":{"heading_path":["Operations","Restart"]}}]} ``` Chunk API 精确读取指定 revision,不回退当前版本;目录分页不返回正文,单块/批量返回有界正文及出处。Batch-get 拒绝重复 ID、 @@ -251,20 +293,56 @@ Chunk API 精确读取指定 revision,不回退当前版本;目录分页不 通用 search 保持框架的 Artifact 引用格式;插件专用 retrieve 提供 chunk 结构。Prepared Context 使用 SearchHit 的片段与 locator, 并遵守字节预算。正常检索先过滤非 active、旧结果及未授权对象,再补取候选;不支持的 filter/rerank 返回明确错误。 -不同 Scope 的查询分别授权,首期不提供聚合接口。Python/HTTP 使用同一业务处理;MCP 与 Dashboard 依框架实际可用能力接入。 +Python/HTTP 复用相同业务语义。通用 search/Prepared Context 保持原有 Scope 契约;空间聚合通过插件 retrieve 提供。 + +### 8.1 空间范围解析与跨库检索 + +1. 未传 space_scope_id 时,解析当前用户默认空间;有值时校验空间可见性。显式 scope_ids 必须全部属于该空间,不能据此反推另一空间。 +2. 未传 scope_ids 时,取空间中调用者可读的知识库;显式空列表表示不查任何库。显式指定无权访问或空间外的库则整次失败, + 不静默忽略。限制库数、请求大小和总返回数量;默认空间、归属和配置需完整,不扩大为全局搜索。 +3. 选定范围内做全文/向量召回与统一融合。固定 embedding profile 时可复用查询向量;使用可比较的评分/统一候选排序, + 不能直接比较各库独立 BM25 的原始分数。先按 Scope 约束候选,再核对 core 权限、active、当前 result_id 和 profile,并补取。 +4. 每条命中携带 space_scope_id、scope_id、document_ref(含 revision)、chunk_id、分数及出处;去重使用完整归属和结果身份, + 相同文件跨库导入不合并其证据。所有精确 chunk 读取仍以知识库 Scope 和 revision 定位。 + +```json +{"space_scope_id":"space-team","scope_ids":["scope-ops","scope-dev"],"query":"How should I restart after a release?","mode":"hybrid","limit":10} +``` + +仅发送 query 表示查询默认空间内所有可读知识库;传 space_scope_id 不传 scope_ids 表示查询该空间的可读知识库。 +聚合路径复用单库权限、生命周期及版本过滤规则,但不依赖嵌套 HTTP 调用。后端故障明确返回失败,首期不承诺部分成功或跨库一致性快照。 + +## 9. Dashboard + +通过 PluginPages 提供知识库页面。界面包含空间/默认空间选择、知识库管理、Markdown/独立图片拖拽上传和本地目录导入、 +文档与请求状态、重试/重解析、分页 chunk 目录与正文、历史查看、同步编辑/移除、文档遗忘及空间内多库检索。 +空间和知识库列表均权限过滤;创建/配置管理要求 server.admin,内容导入要求 scope.contribute,编辑/forget 保留 artifact.write。 +首次导入前就确定有效切块配置,不引入上传后的独立待配置任务队列。 + +文档页面同时展示“当前可用 revision”和“最近处理请求”;失败不隐藏旧有效内容。编辑成功显示新 revision,冲突要求重新读取, +响应未知时先核实结果。移除最后一块允许零块版本。Forget 文案为“移出检索”,历史仍可查看;不展示取消、恢复、整库删除或问答入口。 + +iframe 通过框架客户端调用本插件声明的路由,读取可由插件路由使用 ctx.reads 提供。通用 document PUT/forget 需要有限的框架 +转发适配:只允许已声明插件所属 family 的指定操作,保持当前用户鉴权,传递 If-Match/revision/state_version,校验知识库归属。 +不提供任意 URL 转发或会话凭据。最终仍进入通用 Artifact 操作和同一事务证据路径,不能用普通插件 writer 或异步编辑 Source 替代。 +上传按框架二进制上限分文件处理,服务端限制路径和文件大小,前端不把文件数当作解析完成进度。 -## 9. 升级、实施与验收 +## 10. 初始化、实施与验收 -upgrade(ctx) 负责插件表及索引元数据迁移,维护自己的 schema 版本。迁移可重复执行,多实例通过插件库协调;先兼容新旧代码, -历史 Artifact manifest 和旧 Source 定义仍需读取。首期部署可以重启升级,不以热加载实现完成作为知识库首期前提。 +setup 调用插件自己的幂等初始化及 schema 版本检查;升级迁移由插件部署流程执行,多实例在插件库协调。 +历史 Artifact manifest 和旧 Source 定义仍需读取;版本不兼容时明确拒绝服务。首期重启部署,不依赖 upgrade(ctx) 钩子或热加载。 备份必须同时包含 core、插件库和 OpenDAL 快照;core 的备份不自动覆盖插件数据。 框架实现需满足三后端 ctx.storage、单 family writer、同步修改证据、治理并发校验、Source 定义及路由契约; -未落地部分属于现有框架依赖的实现缺口,不另建知识库锁表、读取 guard 或独立队列。必要适配不得绕过 core 公共约束。 +三后端 ctx.storage、core 保存原始用户编辑载荷(而非生成后 manifest)、Dashboard 通用操作受限转发是明确的框架适配项。 +不另建知识库锁表、读取 guard 或独立队列;适配不得绕过 core 公共约束。 在 SQLite、SeekDB、OceanBase 分别验证: -- 创建 Scope 的管理员权限、配置补写、多 Scope 隔离和固定原文快照。 +- 插件内空间/默认映射并发初始化、默认修改冲突、唯一知识库归属、core 不记录空间父子关系。 +- 空间默认与显式查询、空列表、越权/空间外库拒绝、权限过滤计数、全局 top-k 及带 Scope 的精确引用。 +- Dashboard 沙箱通用操作转发、If-Match 保留、零 chunk 编辑、双状态展示和失败后的旧版本可用性。 +- 创建 Scope 的管理员权限、归属/配置补写、多 Scope 隔离和固定原文快照;两种导入来源的稳定身份及路径约束。 - 导入请求各提交边界的重试、同键冲突、内容去重、重复处理及确定失败不阻塞后续文件。 - 框架窗口回滚/重新投递、失败观察与 core 成功对账;固定 base 冲突不能自动换基准。 - Markdown、真实 RapidOCR、超长块、完整 embedding 输入预算、原文溯源与人工标记。 @@ -274,7 +352,8 @@ upgrade(ctx) 负责插件表及索引元数据迁移,维护自己的 schema - 插件模型指纹不匹配明确失败,Server 主模型变化不改变插件向量空间。 固定 oceanbase/oceanbase 文档 commit 做 Markdown 小样本,配合真实文字图片;mock 不能代替真实 OCR 和三后端验收。 -#2441 覆盖接入/配置,#2442 覆盖框架消费/解析/发布,#2443 覆盖检索/编辑接口,#2444 覆盖运行及验收;#2440 总跟踪。 +#2441 覆盖空间/默认/接入配置,#2442 覆盖框架消费/解析/发布,#2443 覆盖跨库检索/编辑/Dashboard, +#2444 覆盖运行及验收;#2440 总跟踪。 实现可集中在一个 PR,按模块提交并逐步验收;本文不新增 Issue。 # 缺点 @@ -284,7 +363,8 @@ upgrade(ctx) 负责插件表及索引元数据迁移,维护自己的 schema # 设计理由与替代方案 -- Scope 对应知识库,与单 family 插件一致,无需知识库 Artifact 或跨 family 写入。 +- 插件内空间 Scope 组织知识库 Scope;关系与默认映射只存插件表,不使用 core 层级或隐含继承权限。 +- core Scope 对应知识库,与单 family 插件一致,无需知识库 Artifact 或跨 family 写入。 - 复用 generate 和 cursor,使 Artifact 与消费进度在 core 原子提交;插件只记录接受及处理观察,不重复实现调度。 - 同步通用 PUT 提供版本校验和成功操作证据;插件 API 写入不自动具有这些证据语义。 - 原文 Source 与处理请求分开,使重解析不修改原始事实;直接 lineage 和原文溯源的职责明确。 @@ -303,10 +383,10 @@ upgrade(ctx) 负责插件表及索引元数据迁移,维护自己的 schema # 待解决问题 实现时确定 SQL 类型与索引细节、OCR 模型版本、窗口和文件大小、同步编辑时限、API 字节上限;用真实后端验证框架的 -revision/生命周期竞争行为。三后端存储和 upgrade 等 RFC 能力与实现 PR 的差异需在实施前核对,不将提案当成已发布功能。 +revision/生命周期竞争行为。三后端存储、编辑证据、Dashboard 转发在实际 master 上完成适配验收,不将提案当成已发布功能。 这些实现选择不改变 Source 不删除、forget 不增加 revision、同步编辑、固定请求 base 及独立模型的契约。 # 后续可能性 -扩展 Word/PDF 解析、持续采集、跨知识库查询、rerank、邻接上下文、运行中撤销及受控模型迁移。 +扩展 Word/PDF 解析、持续采集、跨空间查询、生成式问答、rerank、邻接上下文、运行中撤销及受控模型迁移。 完整 Source 删除、历史访问撤销、知识库级联删除和独立长任务需要单独确认契约,不作为首期的隐含承诺。 From e136e7d1622fc577dd690ae1cf48e17bbb36a835 Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Sun, 15 Nov 2026 14:52:38 +0800 Subject: [PATCH 12/13] docs(rfc): pin knowledge base space across creation retries --- docs/en/rfcs/2570-knowledge-base.md | 30 +++++++++++++++++++++-------- docs/zh/rfcs/2570-knowledge-base.md | 21 +++++++++++++++----- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index 1ff11c98e9..dac2303de9 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -31,8 +31,8 @@ holds bodies and indexes. Existing scheduling, revision preconditions, and lifec # Guide-level explanation -1. Select a plugin-local space, defaulting to the caller's own default space. An administrator creates a knowledge-base Scope - in that space and saves parsing/chunking configuration. +1. Select a plugin-local space; if the UI has no selection, read the caller's default first and pin space_scope_id for creation. + An administrator creates the knowledge-base Scope there and saves parsing/chunking configuration. 2. Upload files through the Dashboard or import a Server-readable directory; select multiple knowledge bases within the space for retrieval. 3. The plugin saves immutable snapshots, registers Sources, and submits processing-request Sources. Acceptance is not parsing success. 4. Framework generate asynchronously processes Markdown/images, prepares complete chunks and indexes, then publishes a document. @@ -83,7 +83,7 @@ flowchart TD D --> Q[Retrieval and exact chunk reads] ``` -Create through ctx.scopes.create with the existing server.admin requirement; the same idempotency key returns the same Scope. +Create through ctx.scopes.create with server.admin; a key derived from the same full creation identity returns the same Scope. The framework's plugin external reference identifies creator ownership. Scope fields hold title/summary; plugin tables hold business configuration. Retry configuration after a successful Scope creation if its separate write fails; reject imports until configuration is ready. Reuse Scope read/contribute, Artifact write, and framework preconditions. Plugin routes must not @@ -112,9 +112,19 @@ write, permission inheritance, tenant isolation, or cascade deletion. An inacces selection; a space without readable bases returns no hits, never a global fallback. Moving knowledge bases or deleting spaces is not supported initially, avoiding implicit data migrations. -Creating a knowledge base resolves its space, idempotently creates the core Scope, then commits membership/configuration in -plugin storage before reporting readiness. A creation key cannot rebind to another space. Retry incomplete registration using -the same key; a Scope missing membership/configuration cannot receive imports or enter space queries. +The knowledge-base creation POST requires an explicit nonempty space_scope_id; missing/empty values return 422. The server +never resolves the default during creation or retry. Dashboard/other callers first read the default or use an explicit selection, +then pin the space ID, request key, and creation parameters. Automatic retries preserve them even if the user's default changes. + +The full creation identity is (ctx.caller.principal_id, space_scope_id, idempotency_key). Derive a key using versioned canonical +encoding and a digest of that tuple for ctx.scopes.create; core adds the plugin-name prefix itself. Never pass only the client's +raw request key or put space membership into core Scope fields. The same full identity returns the same Scope and must match +existing plugin membership. Different callers/spaces with the same raw key are different creations, never reuse or relocation. + +After validating the space and permissions, idempotently create the core Scope, then commit unique membership/configuration +in plugin storage before reporting readiness. Retry incomplete registration using the pinned space and full creation identity; +a Scope missing membership/configuration cannot receive imports or enter space queries. Queries and knowledge-base lists may +still omit the space and resolve the current default; those read rules never change a creation's pinned target. ## 2. Local storage, identity, and request acceptance @@ -290,7 +300,8 @@ default successful JSON responses may use 200. | --- | --- | | List/create/rename spaces | GET/POST `P/spaces`, PATCH `P/spaces/{space_scope_id}`; plugin-local spaces, writes require idempotency keys or version preconditions | | My default space | GET/PUT `P/me/default-space`; current caller's space_scope_id and version; no caller-supplied principal_id for other users | -| List/create knowledge bases | GET/POST `P/knowledge-bases`; optional space_scope_id, otherwise resolve default; create core Scope and save membership/configuration, returning both IDs | +| List knowledge bases | GET `P/knowledge-bases`; optional space_scope_id, otherwise use the current default | +| Create knowledge base | POST `P/knowledge-bases`; required space_scope_id and idempotency_key; idempotency uses caller + space + request key, returning both IDs | | Rename/configure knowledge base | PATCH `P/scopes/{s}/settings`; ctx.scopes.update for title/summary, plugin storage for chunking, separate version preconditions | | Import files | POST `P/scopes/{s}/imports`, bounded paths and idempotency_key; per-file request SourceRefs | | Browser upload | POST `P/scopes/{s}/uploads`, binary body; collection, relative_path, idempotency_key in query; same acceptance path | @@ -377,7 +388,9 @@ PluginPages provides space/default selection, knowledge-base management, Markdow local-directory import, document/request status, retry/reprocess, paginated chunk metadata/bodies, history viewing, synchronous edit/removal, document forget, and multi-base retrieval within a space. Filter lists by permissions and retain operation-specific access checks: creation/configuration management requires server.admin, imports require scope.contribute, and edit/forget retain -artifact.write. Resolve valid chunking configuration before initial import; no separate post-upload pending-configuration queue. +artifact.write. Pin the selected/default space before submitting creation; retries preserve space_scope_id and the request key. +Changing the creation target is a new user operation. Resolve valid chunking configuration before initial import; no separate +post-upload pending-configuration queue. Display the usable revision separately from the latest request. A failure does not hide previously committed content. Successful edits show the new revision; conflicts require re-reading, and uncertain responses require reconciliation. Removing the final @@ -409,6 +422,7 @@ Validate on SQLite, SeekDB, and OceanBase: - Default/explicit space queries, empty selections, inaccessible/out-of-space rejection, filtered counts, global top-k, scoped citations. - Sandboxed Dashboard generic-operation forwarding, preserved If-Match, zero-chunk edits, separate statuses and usable old revisions. - Administrator-only Scope creation, membership/configuration retry, multi-Scope isolation, snapshots, stable identities/path bounds for both origins. +- Missing creation space returns 422; after core success/plugin failure, changing the default does not redirect the retry; raw keys cannot collide across callers/spaces. - Retries across import acceptance boundaries, key conflicts, content deduplication, repeated handling, and deterministic failures that do not block later files. - Window rollback/redelivery, failure observations versus committed core success, and pinned-base conflicts without automatic rebasing. diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index a943142e28..756efc04fe 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -27,7 +27,7 @@ Dashboard、浏览器上传和空间内跨知识库检索。空间是组织与 # 使用层说明 -1. 用户选择插件内空间,未指定则使用自己的默认空间。管理员在空间中创建知识库 Scope,并保存解析/切块配置。 +1. 用户选择插件内空间;界面未选择时先读取自己的默认空间,再固定 space_scope_id 发起创建。管理员创建知识库 Scope 并保存配置。 2. 用户通过 Dashboard 上传文件,或导入 Server 可访问的本地目录;可在空间内选择多个知识库联合检索。 3. 插件保存不可变原文快照、登记 Source,并提交处理请求 Source;导入接受不等于解析完成。 4. 框架异步调用 generate,处理 Markdown/图片,准备完整 chunks 和索引,再发布 document。 @@ -74,7 +74,7 @@ flowchart TD D --> Q[Retrieval and exact chunk reads] ``` -通过 ctx.scopes.create 创建 Scope,沿用 server.admin 要求;同幂等键返回同一 Scope。框架的插件外部引用标识创建归属。 +通过 ctx.scopes.create 创建 Scope,沿用 server.admin 要求;同完整创建身份派生的幂等键返回同一 Scope。框架的插件外部引用标识创建归属。 标题/摘要使用 Scope 字段,业务配置使用插件表。Scope 创建成功但配置失败时,重试补齐配置;配置未就绪时拒绝导入。 授权沿用 Scope read/contribute、Artifact write 及框架版本校验,插件接口不得将 Scope 贡献权限等同于任意文档修改权限。 @@ -95,8 +95,16 @@ Workspace 可以是英文展示词,不是新增 Artifact family 或另一套 c 归属不授予 Scope read/contribute 或 Artifact write,也不产生权限继承、租户隔离和级联删除。默认空间失去可见性时返回错误并要求 重新选择;没有可读知识库时返回空结果,不回退全局搜索。首期不支持变更知识库所属空间或删除空间,避免隐含跨库数据迁移。 -创建知识库时先解析空间,随后幂等创建 core Scope,并在插件事务内保存唯一归属和配置;全部完成后才报告可用。 -相同创建键不得改绑到其他空间。core 创建成功而插件事务失败时,同键补齐;归属/配置不完整的 Scope 不参与空间查询,也不可导入。 +创建知识库的 POST 必须显式携带非空 space_scope_id;缺失或为空返回 422,服务端不在创建或重试时解析默认空间。 +Dashboard/其他调用者先读取默认空间(或使用用户选择),再固定空间 ID、请求键及创建参数;自动重试原样复用,默认空间切换不改变目标。 + +完整创建身份为 (ctx.caller.principal_id, space_scope_id, idempotency_key)。插件对该元组做带版本的规范化编码和摘要,作为 +ctx.scopes.create 的幂等键;core 自己添加插件名前缀。不能只把客户端裸请求键传给 core,也不把空间关系写入 core Scope 字段。 +同完整身份返回同一 Scope,插件已有归属必须匹配;不同调用者或空间即使裸键相同也是不同创建,不得复用或迁移已有 Scope。 + +验证空间及权限后,幂等创建 core Scope,再在插件事务内保存唯一归属和配置;全部完成后才报告可用。 +core 创建成功而插件事务失败时,使用固定空间和完整创建身份补齐;归属/配置不完整的 Scope 不参与空间查询,也不可导入。 +查询和知识库列表仍允许省略空间并使用当前默认值;创建的固定目标不随这些读取规则变化。 ## 2. 本地存储、身份与请求接受 @@ -238,7 +246,8 @@ Content Source,document revision 增加。修改保留逻辑 chunk ID 和原 | --- | --- | | 空间列表/创建/改名 | GET/POST `P/spaces`、PATCH `P/spaces/{space_scope_id}`;插件内逻辑空间,写入带幂等键或版本前置条件 | | 我的默认空间 | GET/PUT `P/me/default-space`;当前用户的 space_scope_id 和 version,不接受替他人设置的 principal_id | -| 知识库列表/创建 | GET/POST `P/knowledge-bases`,可指定 space_scope_id,否则解析默认空间;创建 core Scope 并保存归属/配置,返回两类 ID | +| 知识库列表 | GET `P/knowledge-bases`,space_scope_id 可省略,使用当前默认空间 | +| 创建知识库 | POST `P/knowledge-bases`,必填 space_scope_id 和 idempotency_key;按调用者+空间+请求键幂等创建,返回两类 ID | | 知识库改名/配置 | PATCH `P/scopes/{s}/settings`;名称/摘要复用 ctx.scopes.update,切块配置存插件;分别使用版本前置条件 | | 导入文件 | POST `P/scopes/{s}/imports`,有界 paths、idempotency_key;返回逐文件请求 SourceRef | | 浏览器上传 | POST `P/scopes/{s}/uploads`,二进制正文,query 携带 collection、relative_path、idempotency_key;复用同一接受流程 | @@ -317,6 +326,7 @@ Python/HTTP 复用相同业务语义。通用 search/Prepared Context 保持 通过 PluginPages 提供知识库页面。界面包含空间/默认空间选择、知识库管理、Markdown/独立图片拖拽上传和本地目录导入、 文档与请求状态、重试/重解析、分页 chunk 目录与正文、历史查看、同步编辑/移除、文档遗忘及空间内多库检索。 空间和知识库列表均权限过滤;创建/配置管理要求 server.admin,内容导入要求 scope.contribute,编辑/forget 保留 artifact.write。 +创建按钮提交前固定所选/默认空间,重试保留原 space_scope_id 和请求键;用户切换创建目标是新的操作。 首次导入前就确定有效切块配置,不引入上传后的独立待配置任务队列。 文档页面同时展示“当前可用 revision”和“最近处理请求”;失败不隐藏旧有效内容。编辑成功显示新 revision,冲突要求重新读取, @@ -343,6 +353,7 @@ setup 调用插件自己的幂等初始化及 schema 版本检查;升级迁移 - 空间默认与显式查询、空列表、越权/空间外库拒绝、权限过滤计数、全局 top-k 及带 Scope 的精确引用。 - Dashboard 沙箱通用操作转发、If-Match 保留、零 chunk 编辑、双状态展示和失败后的旧版本可用性。 - 创建 Scope 的管理员权限、归属/配置补写、多 Scope 隔离和固定原文快照;两种导入来源的稳定身份及路径约束。 +- 创建缺少空间返回 422;core 成功/插件失败后切换默认空间,重试仍完成原空间归属;不同调用者/空间的裸键不碰撞。 - 导入请求各提交边界的重试、同键冲突、内容去重、重复处理及确定失败不阻塞后续文件。 - 框架窗口回滚/重新投递、失败观察与 core 成功对账;固定 base 冲突不能自动换基准。 - Markdown、真实 RapidOCR、超长块、完整 embedding 输入预算、原文溯源与人工标记。 From b9a688a4174352a18f542adf237daede617f10cd Mon Sep 17 00:00:00 2001 From: Frey <370805886@qq.com> Date: Sun, 15 Nov 2026 22:03:36 +0800 Subject: [PATCH 13/13] docs(rfc): align knowledge-base boundaries and recovery contracts --- docs/en/rfcs/2570-knowledge-base.md | 73 +++++++++++++++++++---------- docs/zh/rfcs/2570-knowledge-base.md | 54 ++++++++++++++------- 2 files changed, 85 insertions(+), 42 deletions(-) diff --git a/docs/en/rfcs/2570-knowledge-base.md b/docs/en/rfcs/2570-knowledge-base.md index dac2303de9..49f7343e20 100644 --- a/docs/en/rfcs/2570-knowledge-base.md +++ b/docs/en/rfcs/2570-knowledge-base.md @@ -54,9 +54,12 @@ are out of scope. Restore/merge methods are not implemented initially; generic r Follow [#2549](https://github.com/oceanbase/powercontext/pull/2549) for single-family plugins, Source definitions, writers, models, and storage, and [#2579](https://github.com/oceanbase/powercontext/pull/2579) for routes and Scope management. -Use public master capabilities as the implementation baseline. Dedicated three-backend storage, original edit-payload evidence, -and Dashboard forwarding of generic operations need limited framework adaptation. Initialize through setup without depending -on a framework upgrade hook. [#2617](https://github.com/oceanbase/powercontext/pull/2617) +The required framework contract is specified by [#2659](https://github.com/oceanbase/powercontext/pull/2659) and implemented by +[#2660](https://github.com/oceanbase/powercontext/pull/2660). Merge those dependencies before the knowledge-base implementation; +an older master is not sufficient. Framework storage provisioning, original edit-payload evidence, transaction-bound authorization, +governance concurrency checks, and generic Dashboard Artifact forwarding belong to those framework changes, not this plugin PR. +The plugin consumes public contracts and owns its tables/indexes, snapshots, parsing, retrieval, routes, and pages. Initialize through +setup without depending on a framework upgrade hook. [#2617](https://github.com/oceanbase/powercontext/pull/2617) is a future collection integration, not a prerequisite for explicit local imports. | Object | Model | @@ -108,9 +111,11 @@ and changing one's own default do not require permission to create core Scopes. Personal owners can see their spaces; a caller who can read a contained knowledge base can see its space; administrators can manage empty spaces. Lists/counts include only readable knowledge bases. Membership grants no Scope read/contribute or Artifact -write, permission inheritance, tenant isolation, or cascade deletion. An inaccessible default returns an error requiring a new -selection; a space without readable bases returns no hits, never a global fallback. Moving knowledge bases or deleting spaces -is not supported initially, avoiding implicit data migrations. +write, permission inheritance, tenant isolation, or cascade deletion. An inaccessible default causes implicit knowledge-base lists +and retrieval to fail closed. GET /me/default-space still returns the caller's own saved ID/version with available=false, and +GET /spaces independently lists accessible spaces. The caller explicitly selects a visible space and uses the saved version to +change the default; neither endpoint silently selects another space. A space without readable bases returns no hits, never a global +fallback. Moving knowledge bases or deleting spaces is not supported initially, avoiding implicit data migrations. The knowledge-base creation POST requires an explicit nonempty space_scope_id; missing/empty values return 422. The server never resolves the default during creation or retry. Dashboard/other callers first read the default or use an explicit selection, @@ -129,8 +134,10 @@ still omit the space and resolve the current default; those read rules never cha ## 2. Local storage, identity, and request acceptance OpenDAL fs manages snapshot directories accessible to the importer, Server, and Workers. Original paths are provenance; -parsing reads snapshots only. Enforce root containment and a fixed symlink policy. Save bytes and compute SHA256 before -Source registration; mtime/size cannot replace the content hash. +parsing reads snapshots only. After checking canonical-root containment, open each directory component from the filesystem root +through directory descriptors with O_NOFOLLOW, including ancestors of the allowed root; open the final file relative to that bound +directory. Resolving then reopening an absolute root is insufficient because an ancestor can be replaced by a symlink between +validation and open. Save bytes and compute SHA256 before Source registration; mtime/size cannot replace the content hash. ```text file_key = (scope_id, collection_id, normalized_relative_path) @@ -187,7 +194,7 @@ is always direct lineage. Synchronous edits preserve current lineage and origina ## 4. Plugin storage and models -ctx.storage uses the Server backend: a dedicated SQLite file or a dedicated SeekDB/OceanBase database, precreated by the deployer +ctx.storage follows #2660: a dedicated SQLite file or the SeekDB/OceanBase database powercontext_plugin_knowledge_base, precreated by the deployer when database-creation permission is unavailable. The plugin selects migrations and full-text/vector implementations by backend, without changing existing core schemas. Originals stay in local OpenDAL directories rather than SQL body columns. @@ -199,8 +206,8 @@ without changing existing core schemas. Originals stay in local OpenDAL director | pc_knowledge_base_chunks | Primary key (scope_id, document_id, result_id, chunk_id); ordinal unique within a result; text, text_length, content_digest, heading_path, source_locator, origin, edit_metadata | There are four plugin domain tables; spaces/defaults do not invent core scope_id values. Validate space references in plugin -transactions, use version preconditions for default updates, and atomically initialize a personal space/default without replacing -an existing default. Explicit space-creation keys are scoped to their creator; changed parameters conflict. Reuse the scope +transactions and use version preconditions for default updates. Register the deterministic personal space before its default +mapping; unique keys and idempotent retries repair interruption between these writes without replacing an existing default. Explicit space-creation keys are scoped to their creator; changed parameters conflict. Reuse the scope resource row for membership without an additional relationship table or core schema changes. Resources is a fixed-purpose register, not a generic task framework: scope rows hold configuration/version, document rows stable @@ -210,7 +217,7 @@ to exact revisions for reconciliation, but core determines success. Full-text/ve not additional domain tables. Document content holds only title, original SourceRef, file identity, result_id, chunk count/digest, configuration fingerprints, -manual-edit markers, and applied_request_ref. Neither bodies nor unbounded chunk-ID lists belong in the manifest. Result IDs +manual-edit markers, and applied_request_id. Neither bodies nor unbounded chunk-ID lists belong in the manifest. Result IDs derive from canonical complete results, never from a predicted uncommitted revision number. The plugin independently configures and creates model clients. Deployment supplies credentials; Sources/Artifacts do not store @@ -220,6 +227,9 @@ model compatibility. If existing indexes disagree with deployment configuration, require controlled migration; do not silently replace configuration or mix spaces. Online model switching is not included. Same-profile index repair reads committed chunks. Parsing/chunking configuration may vary by Scope and is pinned in each request. +The framework SQL namespace is plugin-name based, not core-database based. Independent deployments sharing a SQL tenant must +isolate their plugin databases/accounts; changing only the core database does not isolate this plugin's tables. + ## 5. Framework consumption, status, and failure handling Declare on_sources and processing-request inputs; reuse framework generate/Supervisor, Scope bindings, consumption cursors, @@ -233,9 +243,14 @@ bounded file sizes to keep OCR/model windows within limits; arbitrary files are | Deterministic input error such as invalid format or no OCR text | Persist a bounded failure observation and skip that input; normal window acknowledgement permits subsequent requests | | Database, model service, or durable index failure | Raise; core rolls back and the cursor does not advance; framework retries with backoff | | Pinned base changed or document no longer active | Record conflict/skipped, never automatically replace the base; caller submits a new request | -| Core publication completed | Derive published state and exact revision from manifest/history applied_request_ref | +| Core publication completed | Derive published state and exact revision from manifest/history applied_request_id | | Core succeeded but plugin status acknowledgement failed | Reconcile core, not failure or duplicate publication inferred from a missing status | +Status reads first reconcile the pinned base+1 revision and current manifest with applied_request_id. If no publication belongs to +the request and the current revision has advanced past its pinned base or the document is inactive, pending/processing resolves to +failed with a conflict reason. This also repairs status when the cursor committed but the later conflict observation failed; it +requires no redelivery, new table, or automatic rebasing. Restart and same-key receipt replay preserve that outcome. + Display the currently usable revision separately from the latest request status: failed reprocessing does not make an older committed revision unusable. Failure observations describe the latest attempt, not proof of cursor acknowledgement. Plugin status cannot advance consumption or justify skipping unproven core writes. Persistent infrastructure failure may block subsequent windows in the Scope; independent @@ -244,8 +259,9 @@ old Sources remain unchanged. Processing requests express intent, not lineage_on Require no head for first publication. Updates validate the pinned base, original, manual-edit policy, and lifecycle. Framework retries cannot rewrite the request's base or discard policy. If an edit/forget occurs after preparation, publication uses framework -revision/governance concurrency checks and must not reactivate deprecated documents. An implementation unable to protect lifecycle -under races must fix and test its framework adapter; an in-memory plugin lock is not a substitute or evidence of support. +revision/governance concurrency checks and must not reactivate deprecated documents. The framework tracks governance observed by +writer reads and checks it during publication; the plugin passes expected_revision to put and does not invent an +expected_state_version writer argument or a local lock. Lifecycle-race guarantees are an acceptance requirement for #2660. ## 6. Publication and index consistency @@ -299,7 +315,7 @@ default successful JSON responses may use 200. | Operation | API and response | | --- | --- | | List/create/rename spaces | GET/POST `P/spaces`, PATCH `P/spaces/{space_scope_id}`; plugin-local spaces, writes require idempotency keys or version preconditions | -| My default space | GET/PUT `P/me/default-space`; current caller's space_scope_id and version; no caller-supplied principal_id for other users | +| My default space | GET/PUT `P/me/default-space`; current caller's space_scope_id and version; GET adds available; no caller-supplied principal_id for other users | | List knowledge bases | GET `P/knowledge-bases`; optional space_scope_id, otherwise use the current default | | Create knowledge base | POST `P/knowledge-bases`; required space_scope_id and idempotency_key; idempotency uses caller + space + request key, returning both IDs | | Rename/configure knowledge base | PATCH `P/scopes/{s}/settings`; ctx.scopes.update for title/summary, plugin storage for chunking, separate version preconditions | @@ -390,7 +406,9 @@ edit/removal, document forget, and multi-base retrieval within a space. Filter l access checks: creation/configuration management requires server.admin, imports require scope.contribute, and edit/forget retain artifact.write. Pin the selected/default space before submitting creation; retries preserve space_scope_id and the request key. Changing the creation target is a new user operation. Resolve valid chunking configuration before initial import; no separate -post-upload pending-configuration queue. +post-upload pending-configuration queue. Capture the space, knowledge-base Scope, document/revision, and view generation for +asynchronous reads; discard stale results and errors after navigation. Status requests must retain their originating Scope, and +old lists/chunks must not replace the newly selected view. An unavailable default leaves the selector usable for explicit recovery. Display the usable revision separately from the latest request. A failure does not hide previously committed content. Successful edits show the new revision; conflicts require re-reading, and uncertain responses require reconciliation. Removing the final @@ -398,8 +416,10 @@ chunk is valid. Label forget as removal from retrieval with history retained; om and generated-answer controls. The sandboxed iframe calls declared plugin routes through the framework client; reads can wrap ctx.reads. Generic document -PUT/forget requires limited framework forwarding: allow only declared operations on the owning plugin's family, retain the -current caller's authorization, forward If-Match/revision/state_version, and validate knowledge-base ownership. Do not provide +GET/PUT/forget uses #2660 `client.artifacts(method, path, {scopeId, ifMatch, json})` and the host's +`/dashboard/plugins/{name}/artifacts/{scope_id}/{artifact_id}` route. PluginPages does not declare artifact_actions, and the plugin +must not add an /api/_artifacts proxy. The framework restricts operations to the owning family and retains caller authorization, +If-Match/revision/state_version; plugin hooks retain knowledge-base ownership checks. Do not provide arbitrary URL forwarding or session credentials. Invoke the generic Artifact operation and its atomic evidence path; an ordinary plugin writer or asynchronous edit Source is not a substitute. Upload files separately within binary request limits, enforce server-side path/size bounds, and do not present uploaded-file counts as completed parsing progress. @@ -411,14 +431,17 @@ coordination in plugin storage across instances. Preserve historical manifest/So The first phase restarts for deployment and does not depend on an upgrade(ctx) hook or hot reload. Backups must include core, plugin storage, and OpenDAL snapshots; core backups do not automatically cover plugin data. -Framework implementation must supply three-backend ctx.storage, single-family writers, synchronous modification evidence, -governance concurrency checks, Source definitions, and routes. Explicit adaptations are three-backend ctx.storage, evidence -preserving the original caller payload rather than the generated manifest, and restricted Dashboard generic-operation forwarding. -Do not introduce knowledge-base lock tables, read guards, or an independent queue; adapters must preserve core contracts. +#2659/#2660 supply framework storage, synchronous edit evidence, transaction-bound authorization, governance checks, and the +Dashboard Artifact bridge. The knowledge-base PR contains no core runtime, core schema, framework SDK, host, writer, or Dashboard +bridge changes. Repository integration is limited to plugin files, optional dependencies, plugin tests/CI, and usage documentation. +Do not introduce knowledge-base lock tables, read guards, or an independent queue. Verify against the merged framework contracts; +until those dependencies merge, report integration results against the tested framework commit rather than master compatibility. Validate on SQLite, SeekDB, and OceanBase: -- Concurrent plugin-local space/default initialization, default-update conflicts, unique membership, no core space hierarchy. +- Concurrent plugin-local space/default initialization, default-update conflicts, revoked-default recovery without implicit fallback, unique membership, no core space hierarchy. +- Allowed-root and ancestor symlink replacement after validation; delayed Dashboard list/status responses after switching bases. +- Conflict observation failure after cursor commit, including restart and replay; status must not remain processing forever. - Default/explicit space queries, empty selections, inaccessible/out-of-space rejection, filtered counts, global top-k, scoped citations. - Sandboxed Dashboard generic-operation forwarding, preserved If-Match, zero-chunk edits, separate statuses and usable old revisions. - Administrator-only Scope creation, membership/configuration retry, multi-Scope isolation, snapshots, stable identities/path bounds for both origins. @@ -466,7 +489,7 @@ acceptance, not completed parsing; deleting a collection target does not delete Implementation fixes SQL/index details, OCR model versions, window/file sizes, synchronous editing limits, and API byte bounds. Validate revision/lifecycle races on real backends. Check gaps between framework RFCs and implementations, including dedicated -storage, edit evidence, and Dashboard forwarding; proposals are not released capabilities. These choices do not change append-only Sources, forget without +storage, edit evidence, and Dashboard forwarding under #2659/#2660; proposals are not released capabilities. These choices do not change append-only Sources, forget without new revisions, synchronous edits, pinned request bases, or independent models. # Future possibilities diff --git a/docs/zh/rfcs/2570-knowledge-base.md b/docs/zh/rfcs/2570-knowledge-base.md index 756efc04fe..ec72e24f3c 100644 --- a/docs/zh/rfcs/2570-knowledge-base.md +++ b/docs/zh/rfcs/2570-knowledge-base.md @@ -46,8 +46,10 @@ Markdown 内嵌图片 OCR、语义/LLM 切块和几万篇规模评测不在首 遵循 [#2549](https://github.com/oceanbase/powercontext/pull/2549) 的单 family、Source 定义、writer、模型和存储契约, 以及 [#2579](https://github.com/oceanbase/powercontext/pull/2579) 的插件路由和 Scope 管理方向。 -以 master 的公开能力为实现基线;三后端专属存储、原始编辑载荷证据及 Dashboard 通用操作转发需要必要的框架适配。 -初始化使用 setup,首期不依赖框架提供 upgrade 钩子。 +依赖 [#2659](https://github.com/oceanbase/powercontext/pull/2659) 的框架契约及 +[#2660](https://github.com/oceanbase/powercontext/pull/2660) 的实现;先合入框架依赖,再合入知识库实现,旧 master 不足以运行全部功能。 +三后端存储供应、原始编辑载荷证据、事务内鉴权、治理并发校验及 Dashboard 通用 Artifact 转发由框架 PR 提供,知识库 PR 不携带这些改动。 +插件只消费公开契约,管理自己的表与索引、快照、解析、检索、业务 API 和页面。初始化使用 setup,首期不依赖 upgrade 钩子。 [#2617](https://github.com/oceanbase/powercontext/pull/2617) 仅是后续持续采集的接入方向,不是本地显式导入的前置条件。 | 对象 | 模型 | @@ -92,8 +94,10 @@ Workspace 可以是英文展示词,不是新增 Artifact family 或另一套 c 显式空间创建/改名、知识库创建/改名沿用 server.admin;个人默认空间的自动登记与修改自己的默认映射不需要创建 core Scope 的权限。 个人空间对所有者可见;有权读取其中知识库的用户可看到包含它的空间;管理员可以管理空空间。列表和计数仅包含调用者可读的知识库。 -归属不授予 Scope read/contribute 或 Artifact write,也不产生权限继承、租户隔离和级联删除。默认空间失去可见性时返回错误并要求 -重新选择;没有可读知识库时返回空结果,不回退全局搜索。首期不支持变更知识库所属空间或删除空间,避免隐含跨库数据迁移。 +归属不授予 Scope read/contribute 或 Artifact write,也不产生权限继承、租户隔离和级联删除。 +默认空间不可见时,隐式知识库列表和检索仍返回错误;GET /me/default-space 允许读取当前用户自己的已保存 ID/version,并返回 available=false, +GET /spaces 独立列出其他可访问空间。用户显式选择有效空间,以已保存的 version 更新默认值;不自动选库或改变查询范围。 +没有可读知识库时返回空结果,不回退全局搜索。首期不支持变更知识库所属空间或删除空间,避免隐含跨库数据迁移。 创建知识库的 POST 必须显式携带非空 space_scope_id;缺失或为空返回 422,服务端不在创建或重试时解析默认空间。 Dashboard/其他调用者先读取默认空间(或使用用户选择),再固定空间 ID、请求键及创建参数;自动重试原样复用,默认空间切换不改变目标。 @@ -109,7 +113,9 @@ core 创建成功而插件事务失败时,使用固定空间和完整创建身 ## 2. 本地存储、身份与请求接受 OpenDAL fs 管理 Server、导入进程和 Worker 均可访问的本地快照目录。原路径只作出处,解析只读快照。 -拒绝根目录越界并固定符号链接策略;先写快照,对实际字节计算 SHA256,再登记 Source。mtime/size 不能代替 hash。 +先校验规范化根目录的包含关系,再从文件系统根开始,使用目录描述符和 O_NOFOLLOW 逐级打开所有目录,包括允许根目录的祖先, +最后相对于已绑定目录打开文件。不能只 resolve 后重新打开完整根路径,否则校验后替换根目录或祖先为符号链接仍可越界。 +先写快照,对实际字节计算 SHA256,再登记 Source。mtime/size 不能代替 hash。 ```text file_key = (scope_id, collection_id, normalized_relative_path) @@ -155,7 +161,8 @@ Markdown 使用 markdown-it-py 提取标题、段落及来源位置。独立图 ## 4. 插件存储与模型 -ctx.storage 使用与 Server 相同的后端:SQLite 为独立文件,SeekDB/OceanBase 为插件专属库。建库权限不足时由部署者预建。 +ctx.storage 遵循 #2660:SQLite 为独立文件,SeekDB/OceanBase 的插件专属库为 powercontext_plugin_knowledge_base,建库权限不足时由部署者预建。 +SQL 命名空间按插件名隔离,不按 core 数据库名隔离;同一 SQL tenant 中的独立部署必须隔离插件库/账号,仅更换 core 库名不足以隔离插件数据。 插件通过 backend 选择迁移及全文/向量实现,不修改现有核心表。原文件仍在 OpenDAL 本地目录,不塞进 SQL 正文列。 | 插件业务表 | 字段及约束 | @@ -166,14 +173,14 @@ ctx.storage 使用与 Server 相同的后端:SQLite 为独立文件,SeekDB | pc_knowledge_base_chunks | 主键 (scope_id, document_id, result_id, chunk_id);ordinal 同结果唯一;text、text_length、content_digest、heading_path、source_locator、origin、edit_metadata | 共四张插件业务表;空间与默认映射不伪造 core scope_id。空间引用在插件事务内验证;默认更新使用版本前置条件,个人空间/默认映射 -首次创建在一个插件事务内完成;已有默认映射不被初始化覆盖。显式空间创建键按创建者限定,同键不同参数冲突。 +初始化先幂等登记确定身份的个人空间,再登记默认映射;唯一键与重试补齐中断,已有默认映射不被初始化覆盖。显式空间创建键按创建者限定,同键不同参数冲突。 知识库归属复用 resources 的 scope 行,不再增加关系表;不修改核心表。 Resources 是固定用途登记,不是通用任务框架:scope 行保存配置/版本;document 行保存稳定文件身份;request 行保存不可变接受参数、 幂等回执及最近尝试结果。它没有租约、执行 token、领取队列或清理 cursor,也不复制 Artifact 的发布指针与生命周期。 请求结果可以引用精确 revision 供对账,成功事实仍以 core 为准。全文/向量辅助结构属于派生索引,不计入业务表数。 -Document content 只保存标题、原文 SourceRef、文件身份、result_id、chunk 数量/摘要、配置指纹、人工修改标记和 applied_request_ref。 +Document content 只保存标题、原文 SourceRef、文件身份、result_id、chunk 数量/摘要、配置指纹、人工修改标记和 applied_request_id。 正文及无界 chunk ID 列表不进入 manifest。结果 ID 来自规范化完整结果,不能用尚未提交的 revision 号作为存储键。 模型由插件独立配置和创建客户端,密钥来自部署配置,不存入 Source/Artifact。不自动跟随 ctx.models 或 Server 模型变化。 @@ -193,9 +200,13 @@ Document content 只保存标题、原文 SourceRef、文件身份、result_id | 文件格式错误、无文字等确定输入错误 | 保存有界失败观察,跳过该输入;窗口正常确认后继续后续请求 | | 数据库、模型服务、索引持久化故障 | 抛出异常,core 回滚,cursor 不前进,由框架退避重试 | | 固定 base 已变化或文档已非 active | 记录冲突/跳过,不以新 base 自动覆盖;用户重新提交请求 | -| core 发布完成 | 从 manifest/历史中的 applied_request_ref 判定已发布及精确 revision | +| core 发布完成 | 从 manifest/历史中的 applied_request_id 判定已发布及精确 revision | | 发布成功但插件状态未更新 | 根据 core 对账,不能仅凭缺少状态把它判为失败或重复发布 | +状态读取优先核对固定 base+1 revision 及当前 manifest 的 applied_request_id;没有本请求的发布证据,且当前 revision 已越过固定 base +或文档已非 active 时,将 pending/processing 推导为 failed 并返回冲突原因。这样即使 cursor 已提交而随后的冲突观察写入失败, +仍能在查询、同键重放及重启后恢复终态;不依赖重新投递,不新增表,也不自动换 base。 + 文档当前可用 revision 与最新处理请求状态独立展示:重解析失败不会把旧有效版本改成不可用。 资源表的失败是最近尝试观察,不等于 cursor 已确认;不能仅凭插件状态推进消费或跳过尚未证明完成的 core 写入。 基础设施持续故障可能阻塞该 Scope 的后续窗口,这是复用框架的边界,不承诺独立逐文件无限制并发或死信队列。 @@ -203,7 +214,8 @@ Document content 只保存标题、原文 SourceRef、文件身份、result_id 首次发布前确认无 head;更新核对固定 base、原文、人工修改策略和生命周期。框架重试也不能改写请求中的 base 或丢弃策略。 事务外准备后发生编辑/forget 时,发布使用框架的 revision/治理并发校验;不能自动恢复 deprecated 文档。 -若实现不能在竞争中保护生命周期,必须修复框架适配并通过测试,不能用插件内存锁代替或承诺已支持。 +框架跟踪 writer 读取时观察到的治理版本,并在发布时校验;插件向 put 传 expected_revision,不扩展 expected_state_version 参数, +也不用插件内存锁替代框架保证。生命周期竞争保护属于 #2660 的验收前提。 ## 6. 发布与索引一致性 @@ -245,7 +257,7 @@ Content Source,document revision 增加。修改保留逻辑 chunk ID 和原 | 操作 | 接口和返回 | | --- | --- | | 空间列表/创建/改名 | GET/POST `P/spaces`、PATCH `P/spaces/{space_scope_id}`;插件内逻辑空间,写入带幂等键或版本前置条件 | -| 我的默认空间 | GET/PUT `P/me/default-space`;当前用户的 space_scope_id 和 version,不接受替他人设置的 principal_id | +| 我的默认空间 | GET/PUT `P/me/default-space`;当前用户的 space_scope_id 和 version;GET 另返回 available;不接受替他人设置的 principal_id | | 知识库列表 | GET `P/knowledge-bases`,space_scope_id 可省略,使用当前默认空间 | | 创建知识库 | POST `P/knowledge-bases`,必填 space_scope_id 和 idempotency_key;按调用者+空间+请求键幂等创建,返回两类 ID | | 知识库改名/配置 | PATCH `P/scopes/{s}/settings`;名称/摘要复用 ctx.scopes.update,切块配置存插件;分别使用版本前置条件 | @@ -328,12 +340,16 @@ Python/HTTP 复用相同业务语义。通用 search/Prepared Context 保持 空间和知识库列表均权限过滤;创建/配置管理要求 server.admin,内容导入要求 scope.contribute,编辑/forget 保留 artifact.write。 创建按钮提交前固定所选/默认空间,重试保留原 space_scope_id 和请求键;用户切换创建目标是新的操作。 首次导入前就确定有效切块配置,不引入上传后的独立待配置任务队列。 +异步读取固定发起时的空间、知识库 Scope、document/revision 和页面代次;切换后丢弃旧响应及错误。 +状态请求不能改用新选中的 Scope,旧列表/chunk 也不能覆盖新页面。默认空间失效时仍可用选择器显式选择其他空间。 文档页面同时展示“当前可用 revision”和“最近处理请求”;失败不隐藏旧有效内容。编辑成功显示新 revision,冲突要求重新读取, 响应未知时先核实结果。移除最后一块允许零块版本。Forget 文案为“移出检索”,历史仍可查看;不展示取消、恢复、整库删除或问答入口。 -iframe 通过框架客户端调用本插件声明的路由,读取可由插件路由使用 ctx.reads 提供。通用 document PUT/forget 需要有限的框架 -转发适配:只允许已声明插件所属 family 的指定操作,保持当前用户鉴权,传递 If-Match/revision/state_version,校验知识库归属。 +iframe 通过框架客户端调用本插件声明的业务路由。通用 document GET/PUT/forget 使用 #2660 的 +`client.artifacts(method, path, {scopeId, ifMatch, json})`,由宿主 `/dashboard/plugins/{name}/artifacts/{scope_id}/{artifact_id}` 转发。 +PluginPages 不声明 artifact_actions,插件不增加 /api/_artifacts 代理。框架限制所属 family 的操作,保持当前用户鉴权及 +If-Match/revision/state_version;插件 hook 继续校验知识库归属。 不提供任意 URL 转发或会话凭据。最终仍进入通用 Artifact 操作和同一事务证据路径,不能用普通插件 writer 或异步编辑 Source 替代。 上传按框架二进制上限分文件处理,服务端限制路径和文件大小,前端不把文件数当作解析完成进度。 @@ -343,12 +359,16 @@ setup 调用插件自己的幂等初始化及 schema 版本检查;升级迁移 历史 Artifact manifest 和旧 Source 定义仍需读取;版本不兼容时明确拒绝服务。首期重启部署,不依赖 upgrade(ctx) 钩子或热加载。 备份必须同时包含 core、插件库和 OpenDAL 快照;core 的备份不自动覆盖插件数据。 -框架实现需满足三后端 ctx.storage、单 family writer、同步修改证据、治理并发校验、Source 定义及路由契约; -三后端 ctx.storage、core 保存原始用户编辑载荷(而非生成后 manifest)、Dashboard 通用操作受限转发是明确的框架适配项。 -不另建知识库锁表、读取 guard 或独立队列;适配不得绕过 core 公共约束。 +#2659/#2660 提供存储供应、同步编辑证据、事务内鉴权、治理校验和 Dashboard Artifact 桥接。 +知识库 PR 不修改 core runtime/schema、框架 SDK、host、writer 或 Dashboard 桥接;仓库级集成仅包含插件目录、可选依赖、插件测试/CI 及使用文档。 +不另建知识库锁表、读取 guard 或独立队列。依赖未合入时,明确记录测试所用框架提交,不将隔离集成通过表述成当前 master 已兼容。 在 SQLite、SeekDB、OceanBase 分别验证: +- 默认空间失去权限后仍可读取自己的配置并显式切换;隐式查询不自动回退。 +- 校验后允许根目录/祖先被替换为符号链接时拒绝读取;Dashboard 切库后的旧列表/状态响应不污染新页面。 +- cursor 提交后冲突观察写入失败,查询、重放和重启均可恢复失败终态。 + - 插件内空间/默认映射并发初始化、默认修改冲突、唯一知识库归属、core 不记录空间父子关系。 - 空间默认与显式查询、空列表、越权/空间外库拒绝、权限过滤计数、全局 top-k 及带 Scope 的精确引用。 - Dashboard 沙箱通用操作转发、If-Match 保留、零 chunk 编辑、双状态展示和失败后的旧版本可用性。 @@ -394,7 +414,7 @@ setup 调用插件自己的幂等初始化及 schema 版本检查;升级迁移 # 待解决问题 实现时确定 SQL 类型与索引细节、OCR 模型版本、窗口和文件大小、同步编辑时限、API 字节上限;用真实后端验证框架的 -revision/生命周期竞争行为。三后端存储、编辑证据、Dashboard 转发在实际 master 上完成适配验收,不将提案当成已发布功能。 +revision/生命周期竞争行为。三后端存储、编辑证据、Dashboard 转发依照 #2659/#2660 在合入后的 master 上完成验收,不将提案当成已发布功能。 这些实现选择不改变 Source 不删除、forget 不增加 revision、同步编辑、固定请求 base 及独立模型的契约。 # 后续可能性