Files
knowledge-governance/internal/releaseadapter/v071/library_universe.go
T
姚章浩 fba2713b4e
build / build (push) Successful in 1m54s
feat(library): 发布写入支持 WeKnora 0.9.0 schema 134
整库发布写入路径原先按 0.7.1 的固定表集合工作:0.9.0 没有 wiki_log_entries,
Current/清理/编目/整实例指纹都会在不存在表上失败,跨版本闸门也因快照丢掉
SchemaVersion 而失效(未知版本被当作 74)。

改为在装配时解析目标 profile,表集合与清理顺序按解析结果;快照复制与范围改写
带上 SchemaVersion/Profile;跨版本发布显式拒绝并同时点名两个版本。单文档发布包
仍只支持 0.7.1,但改为明确拒绝并说明原因。

本机隔离验证:真实 0.9.0 schema 源库→导出→封存→写入干净 134 目标→逐表核对→
写前镜像回滚;74→134 拒绝与 134 缺表不报错两个负例通过。make verify 17 项全绿。
2026-11-16 20:42:23 +08:00

162 lines
6.0 KiB
Go
Raw 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"
"sort"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/librarysnapshot"
)
// universeFingerprint 是"整实例"的知识域指纹:不限租户/知识库的行数与**逐行内容**摘要。
//
// 为什么不能只比目标范围:恢复只按目标范围删除/回放,写到范围外的残留它看不见
// (真实事故:作业报"已恢复到预备份",目标却多出 4 文件 / 38 分块 / 21 资源 /
// 4 绑定)。整实例指纹让"多写了什么"必然暴露,同时也能证明恢复没有误删、误改
// 别的知识库的行。
//
// 为什么必须是内容而不是身份集合:只比 id 集合时,"另一个知识库的同 ID 行被覆盖
// 写坏"(资源表的 ON CONFLICT 就会这样)在指纹上完全看不出来——数量、身份都一样。
// 因此摘要取自每行 to_jsonb 的 md5,再按身份排序聚合。
func universeFingerprint(ctx context.Context, pool *pgxpool.Pool) (map[string]libraryrelease.TableFingerprint, error) {
// 表集合来自目标库自己的 profile:0.9.0 没有 wiki_log_entries,按 0.7.1 的固定
// 清单取指纹会在第一张不存在的表上失败,而"跳过缺表"又会让 0.7.1 少表蒙混过去。
schema, err := ResolveSchemaProfile(ctx, pool, "whole-instance fingerprint")
if err != nil {
return nil, err
}
result := make(map[string]libraryrelease.TableFingerprint, len(schema.Tables))
for _, table := range schema.Tables {
identity := identityExpr(table)
statement := fmt.Sprintf(
`SELECT count(*), coalesce(md5(string_agg(md5(to_jsonb(x)::text), E'\n' ORDER BY (%s)::text)), '') FROM %s AS x`,
identity, table)
var fingerprint libraryrelease.TableFingerprint
if err := pool.QueryRow(ctx, statement).Scan(&fingerprint.Count, &fingerprint.Digest); err != nil {
return nil, fmt.Errorf("读取整库 %s 指纹失败: %w", table, err)
}
result[table] = fingerprint
}
return result, nil
}
// archivedRowIdentities 读出一份归档部件的行身份(与校验用的身份口径一致)。
func archivedRowIdentities(archive *librarysnapshot.Archive, part librarysnapshot.Part) ([]string, error) {
reader, err := archive.OpenPart(part)
if err != nil {
return nil, err
}
defer reader.Close()
decoder := json.NewDecoder(reader)
token, err := decoder.Token()
if err != nil || token != json.Delim('[') {
return nil, errors.New("归档部件不是行数组")
}
ids := make([]string, 0, 64)
for decoder.More() {
var row map[string]json.RawMessage
if err := decoder.Decode(&row); err != nil {
return nil, err
}
identity, err := parseRowIdentity(part.Name, row)
if err != nil {
return nil, err
}
key := identity.key()
for _, previous := range ids {
if previous == key {
return nil, fmt.Errorf("duplicate %s identity", part.Name)
}
}
ids = append(ids, key)
}
return ids, nil
}
// universeDiff 返回第一处不一致的表;空字符串表示整实例与参照完全一致。
func universeDiff(want, got map[string]libraryrelease.TableFingerprint) string {
tables := make([]string, 0, len(want))
for table := range want {
tables = append(tables, table)
}
sort.Strings(tables)
for _, table := range tables {
current, ok := got[table]
if !ok {
return fmt.Sprintf("%s(目标读不到)", table)
}
if current.Count != want[table].Count {
return fmt.Sprintf("%s 行数 %d,参照 %d", table, current.Count, want[table].Count)
}
if current.Digest != want[table].Digest {
return fmt.Sprintf("%s 身份集合与参照不同(同数量改写也会被这条拦住)", table)
}
}
return ""
}
// assertNoSourceScopeRows 找出"这次要写的这些行,仍然以来源身份躺在目标里"。
//
// 判据按归档里的身份集合逐表核对,而不是"这个租户/知识库有没有行":同一个租户
// 里本来就可能住着别的知识库(共享资源、别的 KB 的绑定),按范围数会把它们误
// 报成残留。这里只认"本次写集合里、仍属于来源租户"的行——它们只可能来自逃出
// 目标范围的写入,而恢复只按目标范围回放,永远删不到它们。
func (t *ProductionLibraryTarget) assertNoSourceScopeRows(ctx context.Context, archive *librarysnapshot.Archive,
manifest librarysnapshot.Manifest) error {
if t.snapshotTenant == 0 {
return nil
}
if t.snapshotTenant == t.scope.TenantID && t.snapshotKB == t.scope.KnowledgeBaseID {
return nil
}
for _, part := range manifest.Parts {
if part.Kind != "database" && part.Kind != "wiki" {
continue
}
if !tableHasTenant(part.Name) {
continue
}
// DB-local source numbers have no target-global ownership meaning.
// The mapped target values are checked by the typed content verifier.
if part.Name == "wiki_log_entries" && t.activePlan != nil && t.activeSnapshot == t.activePlan.TargetSnapshotID {
continue
}
ids, err := archivedRowIdentities(archive, part)
if err != nil {
return err
}
if len(ids) == 0 {
continue
}
// Shared tables have no KB column. Equal tenant identity is not
// evidence of leakage; their ownership is checked by the plan.
if !tablesWithKB[part.Name] && t.snapshotTenant == t.scope.TenantID {
continue
}
cast := "text"
if part.Name == "wiki_log_entries" {
cast = "bigint"
}
statement := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_id=$1 AND id = ANY($2::%s[])`, part.Name, cast)
args := []any{t.snapshotTenant, ids}
if tablesWithKB[part.Name] {
statement += " AND knowledge_base_id=$3"
args = append(args, t.snapshotKB)
}
var count int64
if err := t.pool.QueryRow(ctx, statement, args...).Scan(&count); err != nil {
return fmt.Errorf("检查目标 %s 的来源范围残留失败: %w", part.Name, err)
}
if count > 0 {
return fmt.Errorf("目标 %s 残留 %d 行仍属于来源范围 %d/%s:有写入逃出了目标范围,恢复不会清掉它们",
part.Name, count, t.snapshotTenant, t.snapshotKB)
}
}
return nil
}