Files
knowledge-governance/internal/releaseadapter/v071/library_export.go
Zhero & Rin 73413c59ee
build / build (push) Successful in 2m3s
feat(library): 适配 WeKnora 0.9.1 并搬运编辑历史
- profile 新增 137(由 v090 克隆),声明知识域关联表 copied/derived/excluded 分类。
- 导出前与导入写事务内各跑漏表门禁;未声明有数据拒绝,空表警告写入 WriteSet。
- chunk_revisions/wiki_page_revisions 接入范围改写、目标身份映射、自然键与回滚顺序。
2026-11-30 18:58:01 +08:00

271 lines
14 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package v071
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/jackc/pgx/v5"
)
type librarySnapshotDB interface {
BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)
}
// ExportLibrary reads one PostgreSQL MVCC snapshot, including empty Wiki tables.
// It does not certify semantic quality, freeze Elasticsearch/objects, or authorize
// publication. Those require a separately verified, complete library version.
func ExportLibrary(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity) (PostgresSnapshot, error) {
return ExportLibraryWithReleases(ctx, db, identity, nil)
}
// ExportLibraryWithReleases 与 ExportLibrary 相同,但允许调用方带上精确解除的死信
// 指纹(只影响死信这一项判定,其余结算条件不变)。
func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity, released []string) (PostgresSnapshot, error) {
if db == nil || identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) || identity.KnowledgeID != "" {
return PostgresSnapshot{}, errors.New("invalid library snapshot scope")
}
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return PostgresSnapshot{}, errors.New("begin library snapshot")
}
defer tx.Rollback(context.WithoutCancel(ctx))
// 版本号只用来选 profile;放行条件是随后的表/列能力探测。
profile, err := ResolveSchemaProfile(ctx, tx, "source library")
if err != nil {
return PostgresSnapshot{}, err
}
// 漏表门禁:在同一个只读快照事务里做,避免"检查完又长出未声明表"。
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx, identity, profile.Profile)
if err != nil {
return PostgresSnapshot{}, err
}
for _, warning := range gateWarnings {
log.Printf("library export declared-table gate: %s", warning)
}
if err := verifyRevisionParentClosure(ctx, tx, identity, profile); err != nil {
return PostgresSnapshot{}, err
}
var graph bool
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
return PostgresSnapshot{}, errors.New("source library unavailable")
}
if graph {
return PostgresSnapshot{}, errors.New("Neo4j graph snapshot is not supported")
}
var unsettled, pending, failed int64
if err := tx.QueryRow(ctx, librarySettlementSQL, identity.TenantID, identity.KnowledgeBaseID).Scan(&unsettled, &pending, &failed); err != nil {
return PostgresSnapshot{}, errors.New("read library settlement")
}
if unsettled != 0 || pending != 0 || failed != 0 {
if failed != 0 && unsettled == 0 && pending == 0 {
rows, rowsErr := sourceDeadLetterRows(ctx, tx, identity.TenantID, identity.KnowledgeBaseID)
if rowsErr != nil {
return PostgresSnapshot{}, rowsErr
}
if releasedErr := requireReleased(rows, released); releasedErr != nil {
return PostgresSnapshot{}, releasedErr
}
} else {
return PostgresSnapshot{}, errors.New("library has unfinished or failed processing; semantic acceptance is still required after settlement")
}
}
if err := verifyLibraryRelationalClosure(ctx, tx, identity, false); err != nil {
return PostgresSnapshot{}, err
}
exporter := PostgresExporter{db: tx}
snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name}
snapshot.Catalog, _, err = captureMigrationCatalogFor(ctx, tx, profile.CatalogTables())
if err != nil {
return PostgresSnapshot{}, err
}
if err = validateMigrationCatalogFor(snapshot.Catalog, profile.CatalogTables(), profile.Profile); err != nil {
return PostgresSnapshot{}, err
}
for _, entry := range libraryContentQueries {
// 0.9.0 没有 wiki_log_entries:不产生该部件,也不去查不存在的表。
if !profile.HasTable(entry.name) {
continue
}
rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID)
if err != nil {
return PostgresSnapshot{}, err
}
snapshot.Tables = append(snapshot.Tables, newTableSnapshot(entry.name, rows))
}
// Resources can be owned by a document/chunk or only referenced in body text.
// The latter includes Wiki manual pages, which document bundles used to miss.
var bodies []json.RawMessage
for _, table := range snapshot.Tables {
if !libraryResourceBodyTable(table.Name) {
continue
}
bodies = append(bodies, table.Rows...)
}
handles, err := libraryResourceHandles(bodies)
if err != nil {
return PostgresSnapshot{}, err
}
resources, err := scopedResourceRows(ctx, &exporter, identity, false, bodies,
snapshot.Table("resource_bindings").Rows)
if err != nil {
return PostgresSnapshot{}, err
}
resourceIDs, resourceHandles := map[string]bool{}, map[string]bool{}
for _, raw := range resources {
var row struct {
ID string `json:"id"`
Handle string `json:"handle"`
TenantID uint64 `json:"tenant_id"`
}
if json.Unmarshal(raw, &row) != nil || row.ID == "" || row.TenantID != identity.TenantID || resourceIDs[row.ID] || resourceHandles[row.Handle] {
return PostgresSnapshot{}, errors.New("invalid library resource identity")
}
resourceIDs[row.ID] = true
resourceHandles[row.Handle] = true
}
for _, handle := range handles {
if !resourceHandles[handle] {
return PostgresSnapshot{}, errors.New("library references an unavailable resource")
}
}
for _, raw := range snapshot.Table("resource_bindings").Rows {
var row struct {
ResourceID string `json:"resource_id"`
}
if json.Unmarshal(raw, &row) != nil || !resourceIDs[row.ResourceID] {
return PostgresSnapshot{}, errors.New("library binding references an unavailable resource")
}
}
ids := make([]string, 0, len(resourceIDs))
for id := range resourceIDs {
ids = append(ids, id)
}
if err := verifyLibraryResourceOwners(ctx, tx, ids); err != nil {
return PostgresSnapshot{}, err
}
snapshot.Tables = append(snapshot.Tables, newTableSnapshot("resources", resources))
if err = tx.Commit(ctx); err != nil {
return PostgresSnapshot{}, errors.New("commit library snapshot")
}
return snapshot, nil
}
// Deleted document retract/finalize tasks are scoped to the KB, not a live
// knowledge row. Never join them to only non-deleted documents. Dead letters
// have no resolution marker in this schema, so presence blocks automatically.
const librarySettlementSQL = `SELECT
(SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0)),
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
// verifyRevisionParentClosure 只拒绝"父行完全不存在/父关系错乱"的修订行;
// 父行被软删的修订属于本次范围外(整库只发活跃内容),随父行一起不导出。
// 这与"历史日志按展示事实保留"不同:修订行的 chunk_id/page_id 是结构引用,
// 真缺失只可能是数据异常,不能静默跳过。
func verifyRevisionParentClosure(ctx context.Context, db schemaProbeDB, identity PostgresIdentity, profile SchemaProfile) error {
checks := make([]string, 0, 3)
labels := make([]string, 0, 3)
if profile.HasTable("chunk_revisions") {
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id))`)
labels = append(labels, "chunk_revisions 缺少 chunk 父行")
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND (c.knowledge_id<>r.knowledge_id OR c.knowledge_base_id<>r.knowledge_base_id)))`)
labels = append(labels, "chunk_revisions 与父 chunk 的 knowledge_id/knowledge_base_id 不一致")
}
if profile.HasTable("wiki_page_revisions") {
checks = append(checks, `(SELECT count(*) FROM wiki_page_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND NOT EXISTS (SELECT 1 FROM wiki_pages p WHERE p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id))`)
labels = append(labels, "wiki_page_revisions 缺少 page 父行")
}
if len(checks) == 0 {
return nil
}
var counts = make([]int64, len(checks))
dest := make([]any, len(checks))
for index := range counts {
dest[index] = &counts[index]
}
if err := db.QueryRow(ctx, "/* library-revision-closure */ SELECT "+strings.Join(checks, ", "),
identity.TenantID, identity.KnowledgeBaseID).Scan(dest...); err != nil {
return fmt.Errorf("读取编辑历史父关系失败: %w", err)
}
problems := make([]string, 0, len(counts))
for index, count := range counts {
if count > 0 {
problems = append(problems, fmt.Sprintf("%s:%d 行", labels[index], count))
}
}
if len(problems) > 0 {
return fmt.Errorf("编辑历史存在无法解析的父引用,拒绝整库发布:%v", problems)
}
return nil
}
var libraryContentQueries = []struct{ name, sql string }{
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
{"chunks", `SELECT to_jsonb(c) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
// 编辑历史:只随活跃父行发布。父行被软删(不在本次范围)时不搬它的历史;
// 父行完全缺失属于数据异常,由 verifyRevisionParentClosure 拒绝,不静默跳过。
{"chunk_revisions", `SELECT to_jsonb(r) FROM chunk_revisions r JOIN chunks c ON c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND c.knowledge_base_id=r.knowledge_base_id JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND r.knowledge_id=c.knowledge_id AND c.deleted_at IS NULL AND k.deleted_at IS NULL ORDER BY r.id`},
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
{"resource_bindings", `SELECT to_jsonb(b) FROM resource_bindings b WHERE b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))) ORDER BY b.id`},
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
// 编辑历史:与 chunk_revisions 同一规则(活跃父行 + 真悬挂由守卫拒绝)。
{"wiki_page_revisions", `SELECT to_jsonb(r) FROM wiki_page_revisions r JOIN wiki_pages p ON p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND p.deleted_at IS NULL ORDER BY r.id`},
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`},
}
// F01: resources were previously selected by an OR over a per-row EXISTS that
// re-scanned every body table, so a small KB in a large tenant paid for all
// unrelated resources. The caller now extracts the exact binding ids and body
// handles first; both are indexed identities, never filename guesses.
const libraryResourcesSQL = `SELECT to_jsonb(r) FROM resources r
WHERE r.tenant_id=$1 AND ($4::boolean OR r.deleted_at IS NULL)
AND (r.id=ANY($2::text[]) OR r.handle=ANY($3::text[]))
ORDER BY r.id`
// scopedResourceRows is the single F01 read path: binding ids and body handles
// are extracted once from already scoped rows, then both are resolved through
// indexed resource identities. The old per-resource EXISTS/position filter
// rescanned every body table for every tenant resource.
func scopedResourceRows(ctx context.Context, exporter *PostgresExporter, identity PostgresIdentity,
includeDeleted bool, bodies, bindings []json.RawMessage) ([]json.RawMessage, error) {
handles, err := libraryResourceHandles(bodies)
if err != nil {
return nil, err
}
ids, err := libraryBindingResourceIDs(bindings)
if err != nil {
return nil, err
}
return exporter.queryRows(ctx, libraryResourcesSQL, identity.TenantID, ids, handles, includeDeleted)
}
// libraryBindingResourceIDs reads the exact resource ids owned by the already
// scoped resource_bindings rows. It does not infer ownership from names.
func libraryBindingResourceIDs(rows []json.RawMessage) ([]string, error) {
seen := map[string]bool{}
ids := make([]string, 0, len(rows))
for _, raw := range rows {
var row struct {
ResourceID string `json:"resource_id"`
}
if err := json.Unmarshal(raw, &row); err != nil || row.ResourceID == "" {
return nil, errors.New("invalid scoped resource binding")
}
if !seen[row.ResourceID] {
seen[row.ResourceID] = true
ids = append(ids, row.ResourceID)
}
}
return ids, nil
}