- profile 新增 137(由 v090 克隆),声明知识域关联表 copied/derived/excluded 分类。 - 导出前与导入写事务内各跑漏表门禁;未声明有数据拒绝,空表警告写入 WriteSet。 - chunk_revisions/wiki_page_revisions 接入范围改写、目标身份映射、自然键与回滚顺序。
This commit is contained in:
@@ -274,7 +274,9 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
}
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range pg.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
if libraryResourceBodyTable(table.Name) {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
}
|
||||
references, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
|
||||
@@ -35,7 +35,7 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
rowsByTable[table] = rows
|
||||
if table != "resource_bindings" && table != "knowledge_tag_relations" {
|
||||
if libraryResourceBodyTable(table) {
|
||||
bodies = append(bodies, rows...)
|
||||
}
|
||||
if table == "resource_bindings" {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/libraryprofile"
|
||||
)
|
||||
|
||||
// 漏表门禁:profile 只声明"必须存在什么",不声明"存在但没见过的表怎么办"。
|
||||
// 于是 0.9.0 起 chunk_revisions / wiki_page_revisions 一直被静默跳过。这里用
|
||||
// information_schema 反向扫描所有带知识列的表,按 profile 分类放行;未分类且
|
||||
// 本次范围内有数据就拒绝,空表放行但留下警告。导出前(源库)与导入前(目标库)
|
||||
// 各执行一次。
|
||||
//
|
||||
// 为什么错误不可重试:表没分类是契约缺口,重试不会让分类长出来;必须补 profile
|
||||
// 或明确排除。错误里带表名与行数,运维不用再猜是哪张表。
|
||||
|
||||
const ReleaseUndeclaredKBTableCode = "release_undeclared_kb_table"
|
||||
|
||||
type UndeclaredKBTable struct {
|
||||
Table string
|
||||
Rows int64
|
||||
}
|
||||
|
||||
type UndeclaredKBTableError struct {
|
||||
Tables []UndeclaredKBTable
|
||||
}
|
||||
|
||||
func (e *UndeclaredKBTableError) Error() string {
|
||||
parts := make([]string, 0, len(e.Tables))
|
||||
for _, table := range e.Tables {
|
||||
if table.Rows < 0 {
|
||||
parts = append(parts, table.Table+"(行数无法判定)")
|
||||
continue
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s(%d 行)", table.Table, table.Rows))
|
||||
}
|
||||
return fmt.Sprintf("%s: 未声明的知识域表在本次发布范围内仍有数据:%v;先补 profile 关联表分类并接入整库搬运,或明确排除并写明理由。此错误不可重试。",
|
||||
ReleaseUndeclaredKBTableCode, parts)
|
||||
}
|
||||
|
||||
// knowledgeTableGateMarker 让测试夹具能区分"门禁探测"与"能力探测":两者都查
|
||||
// information_schema.columns,但回答的列形状不同(表+列集合 vs 表+列)。
|
||||
const knowledgeTableGateMarker = "/* knowledge-table-gate */"
|
||||
|
||||
const knowledgeScopedColumnsSQL = knowledgeTableGateMarker + `
|
||||
SELECT c.table_name, array_agg(c.column_name ORDER BY c.column_name)
|
||||
FROM information_schema.columns c
|
||||
JOIN (
|
||||
SELECT DISTINCT table_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema='public' AND column_name IN ('knowledge_base_id','knowledge_id','kb_id')
|
||||
) k ON k.table_name = c.table_name
|
||||
WHERE c.table_schema='public'
|
||||
GROUP BY c.table_name
|
||||
ORDER BY c.table_name`
|
||||
|
||||
// verifyDeclaredKnowledgeTables 返回放行警告(未分类但为空的表);有未分类且
|
||||
// 非空的表时返回 UndeclaredKBTableError。identity 是本知识库范围。
|
||||
func verifyDeclaredKnowledgeTables(ctx context.Context, db schemaProbeDB, identity PostgresIdentity,
|
||||
profile libraryprofile.Profile) ([]string, error) {
|
||||
if identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) {
|
||||
return nil, errors.New("漏表门禁缺少有效的知识库范围身份")
|
||||
}
|
||||
// 没有分类的 profile 不允许"静默跳过门禁":那等于把契约缺口藏起来。
|
||||
if len(profile.RelatedTables) == 0 {
|
||||
return nil, fmt.Errorf("profile %s 没有关联表分类,拒绝跳过漏表门禁", profile.Name)
|
||||
}
|
||||
rows, err := db.Query(ctx, knowledgeScopedColumnsSQL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取知识域表清单失败: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
unclassified := make([]string, 0, 4)
|
||||
columnsByTable := map[string]map[string]bool{}
|
||||
for rows.Next() {
|
||||
var table string
|
||||
var columns []string
|
||||
if err := rows.Scan(&table, &columns); err != nil {
|
||||
return nil, fmt.Errorf("解析知识域表清单失败: %w", err)
|
||||
}
|
||||
if _, ok := profile.RelatedTableClass(table); ok {
|
||||
continue
|
||||
}
|
||||
set := make(map[string]bool, len(columns))
|
||||
for _, column := range columns {
|
||||
set[column] = true
|
||||
}
|
||||
columnsByTable[table] = set
|
||||
unclassified = append(unclassified, table)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("遍历知识域表清单失败: %w", err)
|
||||
}
|
||||
|
||||
blocked := make([]UndeclaredKBTable, 0, len(unclassified))
|
||||
warnings := make([]string, 0, len(unclassified))
|
||||
for _, table := range unclassified {
|
||||
count, ok := scopedKnowledgeTableCountSQL(table, columnsByTable[table], identity)
|
||||
if !ok {
|
||||
// 候选表却没有可用的范围列:无法证明"本次范围内有没有数据",
|
||||
// 只能按有数据处理,避免把范围外的表误放行。
|
||||
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: -1})
|
||||
continue
|
||||
}
|
||||
var total int64
|
||||
if err := db.QueryRow(ctx, count.sql, count.args...).Scan(&total); err != nil {
|
||||
return nil, fmt.Errorf("统计未声明表 %s 失败: %w", table, err)
|
||||
}
|
||||
if total > 0 {
|
||||
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: total})
|
||||
continue
|
||||
}
|
||||
warnings = append(warnings, fmt.Sprintf(
|
||||
"%s: 未分类表 %q 在本次范围内为空,已放行;请补 profile 关联表分类", ReleaseUndeclaredKBTableCode, table))
|
||||
}
|
||||
sort.Slice(blocked, func(i, j int) bool { return blocked[i].Table < blocked[j].Table })
|
||||
sort.Strings(warnings)
|
||||
if len(blocked) > 0 {
|
||||
return nil, &UndeclaredKBTableError{Tables: blocked}
|
||||
}
|
||||
return warnings, nil
|
||||
}
|
||||
|
||||
type scopedCount struct {
|
||||
sql string
|
||||
args []any
|
||||
}
|
||||
|
||||
// scopedKnowledgeTableCountSQL 按"这张表实际有的范围列"构造计数:有
|
||||
// knowledge_base_id 优先按 tenant+kb;有 kb_id 按 tenant+kb_id;只有
|
||||
// knowledge_id 时走 knowledges 子查询。没有 tenant_id 的表(如 kb_shares)
|
||||
// 只能按知识库身份过滤,不能硬塞一个不存在的列。
|
||||
func scopedKnowledgeTableCountSQL(table string, columns map[string]bool,
|
||||
identity PostgresIdentity) (scopedCount, bool) {
|
||||
quoted := pgx.Identifier{"public", table}.Sanitize()
|
||||
hasTenant := columns["tenant_id"]
|
||||
var where string
|
||||
var args []any
|
||||
switch {
|
||||
case columns["knowledge_base_id"]:
|
||||
if hasTenant {
|
||||
where, args = "tenant_id=$1 AND knowledge_base_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
} else {
|
||||
where, args = "knowledge_base_id=$1", []any{identity.KnowledgeBaseID}
|
||||
}
|
||||
case columns["kb_id"]:
|
||||
if hasTenant {
|
||||
where, args = "tenant_id=$1 AND kb_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
} else {
|
||||
where, args = "kb_id=$1", []any{identity.KnowledgeBaseID}
|
||||
}
|
||||
case columns["knowledge_id"]:
|
||||
where = "knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)"
|
||||
args = []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
default:
|
||||
return scopedCount{}, false
|
||||
}
|
||||
return scopedCount{sql: "/* knowledge-table-gate-count */ SELECT count(*) FROM " + quoted + " WHERE " + where, args: args}, true
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"knowledge-governance/internal/libraryprofile"
|
||||
)
|
||||
|
||||
// gateRows 回答门禁的 information_schema 探测:table → 列集合。
|
||||
type gateRows struct {
|
||||
tables [][2]any
|
||||
index int
|
||||
}
|
||||
|
||||
func (r *gateRows) Close() {}
|
||||
func (r *gateRows) Err() error { return nil }
|
||||
func (r *gateRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }
|
||||
func (r *gateRows) FieldDescriptions() []pgconn.FieldDescription { return nil }
|
||||
func (r *gateRows) RawValues() [][]byte { return nil }
|
||||
func (r *gateRows) Conn() *pgx.Conn { return nil }
|
||||
func (r *gateRows) Next() bool {
|
||||
if r.index >= len(r.tables) {
|
||||
return false
|
||||
}
|
||||
r.index++
|
||||
return true
|
||||
}
|
||||
func (r *gateRows) Scan(dest ...any) error {
|
||||
*dest[0].(*string) = r.tables[r.index-1][0].(string)
|
||||
*dest[1].(*[]string) = r.tables[r.index-1][1].([]string)
|
||||
_ = dest
|
||||
return nil
|
||||
}
|
||||
func (r *gateRows) Values() ([]any, error) { return nil, nil }
|
||||
|
||||
type gateCountRow struct{ value *int64 }
|
||||
|
||||
func (r gateCountRow) Scan(dest ...any) error { *dest[0].(*int64) = *r.value; return nil }
|
||||
|
||||
// gateDB 只实现门禁需要的两个入口:探测表/列 + 按表计数。
|
||||
type gateDB struct {
|
||||
candidates []struct {
|
||||
table string
|
||||
columns []string
|
||||
}
|
||||
counts map[string]int64
|
||||
}
|
||||
|
||||
func (d gateDB) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||
if !strings.Contains(sql, "knowledge-table-gate") {
|
||||
return nil, errors.New("unexpected query: " + sql)
|
||||
}
|
||||
rows := &gateRows{}
|
||||
for _, candidate := range d.candidates {
|
||||
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (d gateDB) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||
for table, count := range d.counts {
|
||||
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||
value := count
|
||||
return gateCountRow{value: &value}
|
||||
}
|
||||
}
|
||||
return gateCountRow{value: new(int64)}
|
||||
}
|
||||
|
||||
func gateProfile(t *testing.T) libraryprofile.Profile {
|
||||
t.Helper()
|
||||
profile, err := libraryprofile.For(libraryprofile.V091Version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateRejectsUnclassifiedTableWithRows(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||
},
|
||||
counts: map[string]int64{"mystery_kb_table": 7},
|
||||
}
|
||||
_, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
var blocked *UndeclaredKBTableError
|
||||
if !errors.As(err, &blocked) {
|
||||
t.Fatalf("unclassified table with rows must be refused, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) ||
|
||||
!strings.Contains(err.Error(), "mystery_kb_table") || !strings.Contains(err.Error(), "7 行") {
|
||||
t.Fatalf("error must name code/table/rows, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "不可重试") {
|
||||
t.Fatalf("error must state non-retryable, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateAllowsEmptyUnclassifiedTableWithWarning(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||
},
|
||||
counts: map[string]int64{"mystery_kb_table": 0},
|
||||
}
|
||||
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
if err != nil {
|
||||
t.Fatalf("empty unclassified table must pass: %v", err)
|
||||
}
|
||||
if len(warnings) != 1 || !strings.Contains(warnings[0], "mystery_kb_table") ||
|
||||
!strings.Contains(warnings[0], ReleaseUndeclaredKBTableCode) {
|
||||
t.Fatalf("expected one persisted warning naming the table, got %v", warnings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateAllowsClassifiedTables(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"chunk_images", []string{"knowledge_base_id", "knowledge_id"}},
|
||||
{"sessions", []string{"knowledge_base_id", "tenant_id"}},
|
||||
{"messages", []string{"knowledge_id", "tenant_id"}},
|
||||
{"data_sources", []string{"knowledge_base_id"}},
|
||||
{"chunks", []string{"knowledge_base_id", "knowledge_id"}},
|
||||
},
|
||||
counts: map[string]int64{"sessions": 27, "messages": 90, "chunk_images": 3},
|
||||
}
|
||||
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
if err != nil || len(warnings) != 0 {
|
||||
t.Fatalf("derived/excluded/copied tables must pass silently, got %v/%v", warnings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateRefusesProfileWithoutClassification(t *testing.T) {
|
||||
_, err := verifyDeclaredKnowledgeTables(context.Background(), gateDB{},
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, libraryprofile.Profile{Name: "bare"})
|
||||
if err == nil || !strings.Contains(err.Error(), "分类") {
|
||||
t.Fatalf("a profile without classification must not skip the gate, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedKnowledgeTableCountSQLUsesExistingColumns(t *testing.T) {
|
||||
identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
|
||||
cases := []struct {
|
||||
name string
|
||||
columns map[string]bool
|
||||
wantSQL string
|
||||
want []any
|
||||
}{
|
||||
{"kb+tenant", map[string]bool{"knowledge_base_id": true, "tenant_id": true},
|
||||
`tenant_id=$1 AND knowledge_base_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||
{"kb without tenant", map[string]bool{"knowledge_base_id": true},
|
||||
`knowledge_base_id=$1`, []any{"kb-safe"}},
|
||||
{"kb_id+tenant", map[string]bool{"kb_id": true, "tenant_id": true},
|
||||
`tenant_id=$1 AND kb_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||
{"kb_id without tenant", map[string]bool{"kb_id": true},
|
||||
`kb_id=$1`, []any{"kb-safe"}},
|
||||
{"knowledge only", map[string]bool{"knowledge_id": true},
|
||||
`knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`,
|
||||
[]any{uint64(10000), "kb-safe"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
count, ok := scopedKnowledgeTableCountSQL("t", tc.columns, identity)
|
||||
if !ok || !strings.Contains(count.sql, tc.wantSQL) {
|
||||
t.Fatalf("sql=%q ok=%v, want fragment %q", count.sql, ok, tc.wantSQL)
|
||||
}
|
||||
if !reflect.DeepEqual(count.args, tc.want) {
|
||||
t.Fatalf("args=%v, want %v", count.args, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, ok := scopedKnowledgeTableCountSQL("t", map[string]bool{"id": true}, identity); ok {
|
||||
t.Fatal("a table without any scope column must not be treated as countable")
|
||||
}
|
||||
}
|
||||
|
||||
// 导出路径必须真的执行门禁:候选表有数据时在封存前就失败。
|
||||
type gateExportDB struct {
|
||||
candidates []struct {
|
||||
table string
|
||||
columns []string
|
||||
}
|
||||
counts map[string]int64
|
||||
}
|
||||
|
||||
func (d gateExportDB) BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error) {
|
||||
return &gateExportTx{db: d}, nil
|
||||
}
|
||||
|
||||
type gateExportTx struct {
|
||||
pgx.Tx
|
||||
db gateExportDB
|
||||
}
|
||||
|
||||
func (tx *gateExportTx) Commit(context.Context) error { return nil }
|
||||
func (tx *gateExportTx) Rollback(context.Context) error { return nil }
|
||||
func (tx *gateExportTx) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||
if strings.Contains(sql, "schema_migrations") {
|
||||
return gateSchemaRow{}
|
||||
}
|
||||
for table, count := range tx.db.counts {
|
||||
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||
value := count
|
||||
return gateCountRow{value: &value}
|
||||
}
|
||||
}
|
||||
return gateCountRow{value: new(int64)}
|
||||
}
|
||||
func (tx *gateExportTx) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||
if strings.Contains(sql, "knowledge-table-gate") {
|
||||
rows := &gateRows{}
|
||||
for _, candidate := range tx.db.candidates {
|
||||
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
return legacySchemaProbeRows(), nil
|
||||
}
|
||||
|
||||
type gateSchemaRow struct{}
|
||||
|
||||
func (gateSchemaRow) Scan(dest ...any) error {
|
||||
*dest[0].(*int) = 74
|
||||
*dest[1].(*bool) = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestExportRunsDeclaredTableGateBeforeSealing(t *testing.T) {
|
||||
db := gateExportDB{candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{{"mystery_kb_table", []string{"knowledge_base_id", "tenant_id"}}},
|
||||
counts: map[string]int64{"mystery_kb_table": 2}}
|
||||
_, err := ExportLibrary(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
|
||||
if err == nil || !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) {
|
||||
t.Fatalf("export must fail closed on undeclared table data, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
@@ -34,6 +38,17 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
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")
|
||||
@@ -85,7 +100,7 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
// The latter includes Wiki manual pages, which document bundles used to miss.
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range snapshot.Tables {
|
||||
if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table.Name) {
|
||||
continue
|
||||
}
|
||||
bodies = append(bodies, table.Rows...)
|
||||
@@ -147,13 +162,62 @@ const librarySettlementSQL = `SELECT
|
||||
(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`},
|
||||
|
||||
@@ -103,6 +103,11 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
|
||||
if d.queryError {
|
||||
return nil, errors.New("fixture failure")
|
||||
}
|
||||
// 漏表门禁也查 information_schema,但回答形状是(表,列集合);与能力探测分开打桩,
|
||||
// 否则会被当成两列结果扫描。74 夹具没有任何未分类的知识域表。
|
||||
if strings.Contains(q, "knowledge-table-gate") {
|
||||
return &jsonRows{}, nil
|
||||
}
|
||||
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
|
||||
if strings.Contains(q, "information_schema.columns") {
|
||||
return legacySchemaProbeRows(), nil
|
||||
|
||||
@@ -31,7 +31,11 @@ var migrationIdentityContracts = map[string]rowIdentityContract{
|
||||
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
// 编辑历史:稳定字符串身份;id 是它自己的身份,chunk_id/page_id/knowledge_id
|
||||
// 是引用(由 remapRow 显式映射)。两表都没有 deleted_at。
|
||||
"chunk_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
}
|
||||
|
||||
type typedRowIdentity struct {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -344,12 +345,16 @@ func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string)
|
||||
if name == "resources" {
|
||||
continue
|
||||
}
|
||||
// 只需正文表与绑定表;修订历史按 Q2=B 不参与资源发现,不为它做整表扫描。
|
||||
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||
continue
|
||||
}
|
||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
||||
}
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||
bodies = append(bodies, items...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
@@ -479,6 +484,16 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra
|
||||
return errors.New("开启生产事务失败")
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
// 漏表门禁的最终判定:在写事务内、任何 DELETE 之前。放在事务外检查会留下
|
||||
// "查完到写前"的窗口,未声明表的数据可能在这段时间被写进来。
|
||||
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx,
|
||||
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, warning := range gateWarnings {
|
||||
log.Printf("library import declared-table gate: %s", warning)
|
||||
}
|
||||
for index := len(t.tables) - 1; index >= 0; index-- {
|
||||
table := t.tables[index]
|
||||
if _, ok := parts[table]; !ok {
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestV090ProductionTargetPublishIsolated(t *testing.T) {
|
||||
t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want)
|
||||
}
|
||||
}
|
||||
call("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
||||
call("PUT", "/"+index, `{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
||||
defer func() {
|
||||
call("DELETE", "/"+index, "", 200)
|
||||
call("HEAD", "/"+index, "", 404)
|
||||
@@ -375,7 +375,7 @@ func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA stri
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
source, err := json.Marshal(map[string]any{
|
||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
||||
"chunk_id": chunk.ID,
|
||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
"embedding": []float64{0.1, 0.2},
|
||||
|
||||
@@ -57,6 +57,10 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
|
||||
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
|
||||
}
|
||||
if source.Table("chunk_revisions").RowCount != 1 || source.Table("wiki_page_revisions").RowCount != 1 {
|
||||
t.Fatalf("editing history must be exported: chunk_revisions=%d wiki_page_revisions=%d",
|
||||
source.Table("chunk_revisions").RowCount, source.Table("wiki_page_revisions").RowCount)
|
||||
}
|
||||
|
||||
es := v090IndexSnapshot(t, source, mappingSHA)
|
||||
root := t.TempDir()
|
||||
@@ -90,6 +94,13 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
|
||||
}
|
||||
}
|
||||
seenParts := map[string]bool{}
|
||||
for _, part := range manifest.Parts {
|
||||
seenParts[part.Kind+"/"+part.Name] = true
|
||||
}
|
||||
if !seenParts["database/chunk_revisions"] || !seenParts["wiki/wiki_page_revisions"] {
|
||||
t.Fatalf("revision parts must be archived: %v", seenParts)
|
||||
}
|
||||
|
||||
dst := v090Pool(t, "KG_V090_TARGET_DSN")
|
||||
if err := seedV090Binding(t, ctx, dst); err != nil {
|
||||
@@ -100,14 +111,21 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
|
||||
if err := importer.Replace(ctx, document, source); err != nil {
|
||||
// 文档级 Replace 只写单文档相关表;编辑历史走整库 Apply(0.9.0 发布目标用例覆盖)。
|
||||
documentSource := withoutRevisionTables(source)
|
||||
if err := importer.Replace(ctx, document, documentSource); err != nil {
|
||||
t.Fatalf("import 0.9.0 snapshot: %v", err)
|
||||
}
|
||||
reloaded, err := ExportLibrary(ctx, dst, identity)
|
||||
if err != nil {
|
||||
t.Fatalf("re-export imported library: %v", err)
|
||||
}
|
||||
compareSnapshotContent(t, source, reloaded)
|
||||
compareSnapshotContent(t, documentSource, withoutRevisionTables(reloaded))
|
||||
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||
if reloaded.Table(table).RowCount != 0 {
|
||||
t.Fatalf("document-level import must not invent %s rows", table)
|
||||
}
|
||||
}
|
||||
|
||||
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
|
||||
var defaults int
|
||||
@@ -130,7 +148,7 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
}
|
||||
|
||||
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
|
||||
crossVersion := source
|
||||
crossVersion := documentSource
|
||||
crossVersion.SchemaVersion = 74
|
||||
crossVersion.Profile = "v071"
|
||||
err = importer.Replace(ctx, document, crossVersion)
|
||||
@@ -139,6 +157,18 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func withoutRevisionTables(snapshot PostgresSnapshot) PostgresSnapshot {
|
||||
tables := make([]TableSnapshot, 0, len(snapshot.Tables))
|
||||
for _, table := range snapshot.Tables {
|
||||
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||
continue
|
||||
}
|
||||
tables = append(tables, table)
|
||||
}
|
||||
snapshot.Tables = tables
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
|
||||
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
|
||||
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
||||
@@ -147,6 +177,9 @@ func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
||||
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
|
||||
}
|
||||
for _, table := range source.Tables {
|
||||
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||
continue
|
||||
}
|
||||
want := tableDigests(t, table.Name, table.Rows)
|
||||
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
|
||||
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
|
||||
|
||||
@@ -9,13 +9,26 @@ import (
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// libraryResourceBodyTable 报告该表是否参与"正文引用资源"的发现与作用域。
|
||||
//
|
||||
// 编辑历史按人类裁定(Q2=B)原样保留 resource:// 文本,不参与资源发现:历史版本
|
||||
// 引用的对象可能早已删除,不能让它决定本次发布必须携带哪些对象。资源发现、目标
|
||||
// 资源作用域、恢复保护三处必须用同一个判定,否则导出与校验会各算一套集合。
|
||||
func libraryResourceBodyTable(table string) bool {
|
||||
switch table {
|
||||
case "resources", "resource_bindings", "knowledge_tag_relations", "chunk_revisions", "wiki_page_revisions":
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Keep capture/verification and deletion protection on the same set of bodies.
|
||||
// predicate is an internal SQL fragment, never caller-supplied content; tables comes
|
||||
// from the resolved schema profile (0.9.0 has no wiki_log_entries to scan).
|
||||
func libraryResourceBodyReferenceSQL(tables []string, predicate string) string {
|
||||
queries := []string{}
|
||||
for _, table := range tables {
|
||||
if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table) {
|
||||
continue
|
||||
}
|
||||
queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate))
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func revisionMapper() *targetIDMapper {
|
||||
mapper := newTargetIDMapper(10001, "kb-target", nil)
|
||||
for table, ids := range map[string][]string{
|
||||
"knowledges": {"doc-src"},
|
||||
"chunks": {"chunk-src"},
|
||||
"wiki_pages": {"page-src"},
|
||||
"chunk_revisions": {"crev-src"},
|
||||
"wiki_page_revisions": {"wrev-src"},
|
||||
} {
|
||||
for _, id := range ids {
|
||||
mapper.registerSourceID(table, id)
|
||||
}
|
||||
}
|
||||
return mapper
|
||||
}
|
||||
|
||||
func TestRevisionRowsUseTheSameScopeAndIdentityMapping(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
chunkRevision := map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"crev-src"`),
|
||||
"knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`),
|
||||
"revision": json.RawMessage(`3`),
|
||||
"content": json.RawMessage(`"edit history text"`),
|
||||
"editor_id": json.RawMessage(`"user-9"`),
|
||||
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||
}
|
||||
if err := mapper.remapRow("chunk_revisions", chunkRevision); err != nil {
|
||||
t.Fatalf("chunk revision mapping: %v", err)
|
||||
}
|
||||
if string(chunkRevision["id"]) != `"`+mapper.mapID("chunk_revisions", "crev-src")+`"` {
|
||||
t.Fatal("revision id must be target-mapped")
|
||||
}
|
||||
if string(chunkRevision["chunk_id"]) != `"`+mapper.mapID("chunks", "chunk-src")+`"` {
|
||||
t.Fatal("chunk_id must map to the target chunk identity")
|
||||
}
|
||||
if string(chunkRevision["knowledge_id"]) != `"`+mapper.mapID("knowledges", "doc-src")+`"` {
|
||||
t.Fatal("knowledge_id must map to the target knowledge identity")
|
||||
}
|
||||
// editor_id 是用户身份,原样保留(目标查不到显示未知编辑者)。
|
||||
if string(chunkRevision["editor_id"]) != `"user-9"` {
|
||||
t.Fatal("editor_id must be preserved")
|
||||
}
|
||||
|
||||
pageRevision := map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"wrev-src"`),
|
||||
"page_id": json.RawMessage(`"page-src"`),
|
||||
"slug": json.RawMessage(`"legacy-slug"`),
|
||||
"version": json.RawMessage(`2`),
|
||||
"content": json.RawMessage(`"wiki history"`),
|
||||
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||
}
|
||||
if err := mapper.remapRow("wiki_page_revisions", pageRevision); err != nil {
|
||||
t.Fatalf("wiki page revision mapping: %v", err)
|
||||
}
|
||||
if string(pageRevision["page_id"]) != `"`+mapper.mapID("wiki_pages", "page-src")+`"` {
|
||||
t.Fatal("page_id must map to the target page identity")
|
||||
}
|
||||
if string(pageRevision["slug"]) != `"legacy-slug"` {
|
||||
t.Fatal("slug is content, not identity; it must be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionDanglingReferencesAreRefused(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
cases := []struct {
|
||||
name string
|
||||
row map[string]json.RawMessage
|
||||
}{
|
||||
{"unknown chunk", map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"crev-unknown"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-other"`), "revision": json.RawMessage(`1`),
|
||||
}},
|
||||
{"unknown page", map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"wrev-unknown"`), "page_id": json.RawMessage(`"page-other"`),
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
table := "chunk_revisions"
|
||||
if tc.name == "unknown page" {
|
||||
table = "wiki_page_revisions"
|
||||
}
|
||||
err := mapper.remapRow(table, tc.row)
|
||||
if !errors.Is(err, errUnmappedTargetReference) || !strings.Contains(err.Error(), "unmapped") {
|
||||
t.Fatalf("dangling reference must be refused, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionUniqueIndexKeysStayUniqueAfterMapping(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
// 同一 chunk 的两个 revision:chunk_id 映射后仍相同,revision 仍是 1/2,
|
||||
// 因此 (chunk_id, revision) 唯一性不会被映射破坏。
|
||||
rows := []map[string]json.RawMessage{
|
||||
{"id": json.RawMessage(`"crev-src"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`1`)},
|
||||
{"id": json.RawMessage(`"crev-src2"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`2`)},
|
||||
}
|
||||
mapper.registerSourceID("chunk_revisions", "crev-src2")
|
||||
mapped := map[string]bool{}
|
||||
for _, row := range rows {
|
||||
if err := mapper.remapRow("chunk_revisions", row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := string(row["chunk_id"]) + "/" + string(row["revision"])
|
||||
if mapped[key] {
|
||||
t.Fatalf("mapped unique key collided: %s", key)
|
||||
}
|
||||
mapped[key] = true
|
||||
}
|
||||
if len(mapped) != 2 {
|
||||
t.Fatal("both revision keys must remain distinct")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionTablesAreDeletedBeforeParents(t *testing.T) {
|
||||
position := map[string]int{}
|
||||
for index, table := range jobCreatedRowDeleteOrder {
|
||||
position[table] = index
|
||||
}
|
||||
for _, child := range []string{"wiki_page_revisions", "chunk_revisions"} {
|
||||
if _, ok := position[child]; !ok {
|
||||
t.Fatalf("%s missing from recovery delete order", child)
|
||||
}
|
||||
}
|
||||
if position["chunk_revisions"] > position["chunks"] {
|
||||
t.Fatal("chunk_revisions must be deleted before chunks")
|
||||
}
|
||||
if position["wiki_page_revisions"] > position["wiki_pages"] {
|
||||
t.Fatal("wiki_page_revisions must be deleted before wiki_pages")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionTablesAreNotResourceBodies(t *testing.T) {
|
||||
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||
if libraryResourceBodyTable(table) {
|
||||
t.Fatalf("%s must not participate in resource discovery (Q2=B)", table)
|
||||
}
|
||||
}
|
||||
sql := libraryResourceBodyReferenceSQL([]string{"chunks", "chunk_revisions", "wiki_page_revisions"}, "TRUE")
|
||||
if strings.Contains(sql, "chunk_revisions") || strings.Contains(sql, "wiki_page_revisions") {
|
||||
t.Fatalf("resource reference SQL must exclude revision tables: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "FROM chunks") {
|
||||
t.Fatal("resource reference SQL must still scan live chunks")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructuredReferenceValidationCoversRevisions(t *testing.T) {
|
||||
snapshot := PostgresSnapshot{Tables: []TableSnapshot{
|
||||
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-1"}`),
|
||||
}),
|
||||
newTableSnapshot("wiki_pages", []json.RawMessage{json.RawMessage(`{"id":"page-1"}`)}),
|
||||
newTableSnapshot("wiki_page_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"wrev-1","page_id":"page-1"}`),
|
||||
}),
|
||||
}}
|
||||
if err := validateLibraryStructuredReferences(snapshot); err != nil {
|
||||
t.Fatalf("resolved revision references must pass: %v", err)
|
||||
}
|
||||
broken := snapshot
|
||||
broken.Tables = []TableSnapshot{
|
||||
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-missing"}`),
|
||||
}),
|
||||
}
|
||||
if err := validateLibraryStructuredReferences(broken); err == nil || !strings.Contains(err.Error(), "chunk_id") {
|
||||
t.Fatalf("missing chunk parent must be refused, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
var tablesWithKB = map[string]bool{
|
||||
"knowledges": true, "chunks": true, "knowledge_tags": true,
|
||||
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
|
||||
"chunk_revisions": true, "wiki_page_revisions": true,
|
||||
}
|
||||
|
||||
// tableHasTenant 报告这张表是否自带租户列。
|
||||
|
||||
@@ -90,6 +90,21 @@ func validateLibraryStructuredReferences(pg PostgresSnapshot) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 编辑历史:chunk_id/page_id 是结构引用,不是展示事实。父行不在本快照里
|
||||
// (软删父行按导出规则不出现)就拒绝;chunk 还必须与 revision.knowledge_id 同文档。
|
||||
for _, r := range tables["chunk_revisions"] {
|
||||
if e := ref(r, "knowledge_id", "knowledges", false); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := ref(r, "chunk_id", "chunks", true); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_page_revisions"] {
|
||||
if e := ref(r, "page_id", "wiki_pages", false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_folders"] {
|
||||
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
||||
return e
|
||||
|
||||
@@ -173,6 +173,26 @@ func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage)
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "chunk_revisions":
|
||||
// 编辑历史与正文走同一套映射:自身身份 + 父文档/父分块引用。
|
||||
// editor_id 是用户身份,原样保留(目标查不到就显示未知编辑者)。
|
||||
if err := m.remapScalar(row, "id", table); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "knowledge_id", "knowledges"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "chunk_id", "chunks"); err != nil {
|
||||
return err
|
||||
}
|
||||
case "wiki_page_revisions":
|
||||
// 自身身份 + page 引用;slug/正文/版本号/aliases 原样保留。
|
||||
if err := m.remapScalar(row, "id", table); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "page_id", "wiki_pages"); err != nil {
|
||||
return err
|
||||
}
|
||||
case "wiki_log_entries":
|
||||
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
|
||||
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
|
||||
|
||||
@@ -80,12 +80,15 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta
|
||||
if name == "resources" {
|
||||
continue
|
||||
}
|
||||
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||
continue
|
||||
}
|
||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err)
|
||||
}
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||
bodies = append(bodies, items...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
|
||||
@@ -122,6 +122,13 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
t.targetIDMode = libraryrelease.TargetIDModeScoped
|
||||
// 漏表门禁:写第一笔之前的预检。导入事务里还会再查一次(写前最终判定),
|
||||
// 这里负责尽早失败,并把"空表放行"的警告写进持久发布记录。
|
||||
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, t.pool,
|
||||
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
@@ -152,7 +159,8 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target,
|
||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||
BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID,
|
||||
CreatedAt: t.now().UTC(), Universe: plan.Universe, TargetIDMode: libraryrelease.TargetIDModeScoped}
|
||||
CreatedAt: t.now().UTC(), Universe: plan.Universe, Warnings: gateWarnings,
|
||||
TargetIDMode: libraryrelease.TargetIDModeScoped}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "database" && part.Kind != "wiki" {
|
||||
continue
|
||||
@@ -350,6 +358,14 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
|
||||
return nil
|
||||
}
|
||||
|
||||
// jobCreatedRowDeleteOrder 是恢复清理的顺序契约:子表先删。编辑历史必须排在
|
||||
// 父表 chunks/wiki_pages 之前;顺序写死在一处,并有单测防止新增表时漏改。
|
||||
var jobCreatedRowDeleteOrder = []string{
|
||||
"wiki_page_revisions", "chunk_revisions", "resource_bindings", "chunks", "knowledges",
|
||||
"knowledge_tag_relations", "wiki_page_issues", "wiki_log_entries", "wiki_pages",
|
||||
"wiki_folders", "knowledge_tags", "resources",
|
||||
}
|
||||
|
||||
// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
|
||||
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
|
||||
// 使用的资源不能删)。
|
||||
@@ -365,9 +381,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
|
||||
// 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。
|
||||
for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations",
|
||||
"wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} {
|
||||
for _, table := range jobCreatedRowDeleteOrder {
|
||||
ids := make([]string, 0, 8)
|
||||
for _, id := range set.CreatedIDs(table) {
|
||||
if restored[table][id] {
|
||||
|
||||
@@ -84,6 +84,8 @@ const v090Folder = "wf-v090-1"
|
||||
const v090Page = "wp-v090-1"
|
||||
const v090Tag = "tg-v090-1"
|
||||
const v090Resource = "rs-v090-1"
|
||||
const v090ChunkRevision = "cr-v090-1"
|
||||
const v090PageRevision = "wr-v090-1"
|
||||
|
||||
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
|
||||
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
|
||||
@@ -99,6 +101,8 @@ func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdent
|
||||
`INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`,
|
||||
`INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`,
|
||||
`INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`,
|
||||
`INSERT INTO chunk_revisions(id,tenant_id,knowledge_base_id,knowledge_id,chunk_id,revision,content,editor_id,edit_source) VALUES ('` + v090ChunkRevision + `',$1,'` + v090KB + `','` + v090Knowledge + `','` + v090ChunkOne + `',1,'第一段旧正文','editor-a','user')`,
|
||||
`INSERT INTO wiki_page_revisions(id,tenant_id,knowledge_base_id,page_id,slug,version,title,content,edit_source,editor_id) VALUES ('` + v090PageRevision + `',$1,'` + v090KB + `','` + v090Page + `','fixture-page',1,'夹具页','旧 wiki 正文','pipeline','')`,
|
||||
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
@@ -166,7 +170,7 @@ func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) Sea
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
source, err := json.Marshal(map[string]any{
|
||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
||||
"chunk_id": chunk.ID,
|
||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user