Files
knowledge-governance/internal/releaseadapter/v071/remap_test.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

199 lines
8.2 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 (
"encoding/json"
"strings"
"testing"
releaseworkflow "knowledge-governance/internal/workflows/release"
)
// crossBaseBundle is an export fixture whose rows and documents carry the base
// identity the way a real v0.7.1 export does (to_jsonb of every column), which
// is what a 源库 → 目标库 remap has to rewrite.
func crossBaseBundle(t *testing.T) *DocumentBundle {
t.Helper()
pg := PostgresSnapshot{Tables: []TableSnapshot{
newTableSnapshot("knowledges", mustCanonicalRows(t, `{"id":"knowledge-safe","knowledge_base_id":"kb-safe","title":"synthetic release marker"}`)),
newTableSnapshot("chunks", mustCanonicalRows(t,
`{"id":"chunk-safe","knowledge_base_id":"kb-safe","embedding":[0.5,-1,1024]}`,
`{"id":"chunk-two","knowledge_base_id":"kb-safe","embedding":[0.25]}`)),
newTableSnapshot("knowledge_tags", mustCanonicalRows(t, `{"id":"tag-safe","knowledge_base_id":"kb-safe"}`)),
newTableSnapshot("wiki_pages", mustCanonicalRows(t, `{"id":"page-safe","knowledge_base_id":"kb-safe"}`)),
newTableSnapshot("wiki_folders", mustCanonicalRows(t, `{"id":"folder-safe","knowledge_base_id":"kb-safe"}`)),
newTableSnapshot("resources", mustCanonicalRows(t, `{"id":"res-safe","physical_path":"storage://backend/oss://bucket/weknora/10000/knowledge-safe/asset"}`)),
}}
search := SearchSnapshot{Documents: []SearchDocument{{
ID: "es-safe",
Source: mustCanonicalRows(t, `{"tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"knowledge-safe","embedding":[0.5,-1,1024]}`)[0],
}}}
search.DocumentsSHA256, _ = searchDocumentsDigest(search.Documents)
search.MappingSHA256 = strings.Repeat("a", 64)
exporter, err := NewDocumentExporter(DocumentExporterConfig{
Contract: &stubSourceContract{contract: sourceContractFixture(search.MappingSHA256)},
Postgres: &stubPGExporter{snapshot: pg}, Search: &stubSearchExporter{snapshot: search},
Objects: &stubObjectExporter{snapshot: ObjectSnapshot{SHA256: objectSnapshotDigest(nil)}},
TenantID: 10000, EmbeddingModel: "bge-m3", Now: fixedArchiveTime,
})
if err != nil {
t.Fatal(err)
}
value, err := exporter.Export(t.Context(), releasePlanForArchive())
if err != nil {
t.Fatal(err)
}
return value.(*DocumentBundle)
}
func rowField(t *testing.T, row json.RawMessage, field string) string {
t.Helper()
var object map[string]json.RawMessage
if err := json.Unmarshal(row, &object); err != nil {
t.Fatal(err)
}
var value string
if err := json.Unmarshal(object[field], &value); err != nil {
t.Fatal(err)
}
return value
}
// The whole point of the production binding: a knowledge verified in one base
// can be written into a DIFFERENT one, with every row and document moved over
// and the bundle re-sealed so the fail-closed checks still hold.
func TestRemapKnowledgeBaseRewritesAllChannelsAndReseals(t *testing.T) {
bundle := crossBaseBundle(t)
sourceBundleSHA := bundle.Manifest.BundleSHA256
chunkBefore := string(bundle.Postgres.Table("chunks").Rows[0])
resourceBefore := string(bundle.Postgres.Table("resources").Rows[0])
if err := bundle.RemapKnowledgeBase("prod-kb"); err != nil {
t.Fatalf("remap: %v", err)
}
// The manifest keeps the SOURCE base: that is where the content came from and
// what the release item's tested base is checked against.
if got := bundle.Manifest.Contract.KnowledgeBaseID; got != "kb-safe" {
t.Fatalf("manifest base = %q, want the source base", got)
}
for _, name := range remappableTables {
table := bundle.Postgres.Table(name)
if len(table.Rows) == 0 {
t.Fatalf("table %s lost its rows", name)
}
for _, row := range table.Rows {
if got := rowField(t, row, knowledgeBaseField); got != "prod-kb" {
t.Fatalf("%s row base = %q, want prod-kb", name, got)
}
if strings.Contains(string(row), "kb-safe") {
t.Fatalf("%s row still mentions the source base: %s", name, row)
}
}
}
// Tables without a base column are carried through untouched.
if got := string(bundle.Postgres.Table("resources").Rows[0]); got != resourceBefore {
t.Fatalf("resources row changed: %s", got)
}
// Embeddings must survive byte-for-byte: only the identity field is rewritten.
var before, after map[string]json.RawMessage
if err := json.Unmarshal([]byte(chunkBefore), &before); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(bundle.Postgres.Table("chunks").Rows[0], &after); err != nil {
t.Fatal(err)
}
if string(before["embedding"]) != string(after["embedding"]) {
t.Fatalf("embedding payload was re-encoded: %s -> %s", before["embedding"], after["embedding"])
}
document := bundle.Search.Documents[0]
if got := rowField(t, document.Source, knowledgeBaseField); got != "prod-kb" {
t.Fatalf("document base = %q, want prod-kb", got)
}
// Every digest the target verifies against is recomputed and re-sealed.
if err := validateDocumentBundle(bundle); err != nil {
t.Fatalf("remapped bundle must stay self-consistent: %v", err)
}
recomputed, err := searchDocumentsDigest(bundle.Search.Documents)
if err != nil || recomputed != bundle.Search.DocumentsSHA256 || recomputed != bundle.Manifest.Search.SHA256 {
t.Fatalf("search digest not coherent: %v %s %s", err, recomputed, bundle.Manifest.Search.SHA256)
}
if bundle.Manifest.BundleSHA256 == sourceBundleSHA {
t.Fatal("bundle digest must change when the content identity changes")
}
}
// A same-base release (the historical semantics) must not touch the bundle at all.
func TestRemapKnowledgeBaseIsNoOpForSameBase(t *testing.T) {
bundle := crossBaseBundle(t)
before := bundle.Manifest.BundleSHA256
if err := bundle.RemapKnowledgeBase("kb-safe"); err != nil {
t.Fatal(err)
}
if bundle.Manifest.BundleSHA256 != before {
t.Fatalf("same-base remap changed the bundle digest")
}
}
func TestRemapKnowledgeBaseFailsClosed(t *testing.T) {
tests := []struct {
name string
mutate func(*DocumentBundle)
target string
}{
{name: "invalid target", target: "prod/kb", mutate: func(*DocumentBundle) {}},
{name: "empty target", target: "", mutate: func(*DocumentBundle) {}},
{name: "row outside the source base", target: "prod-kb", mutate: func(bundle *DocumentBundle) {
bundle.Postgres = replaceTable(bundle.Postgres, newTableSnapshot("chunks", mustCanonicalRows(t, `{"id":"chunk-safe","knowledge_base_id":"other-kb"}`)))
}},
{name: "row without an identity", target: "prod-kb", mutate: func(bundle *DocumentBundle) {
bundle.Postgres = replaceTable(bundle.Postgres, newTableSnapshot("knowledges", mustCanonicalRows(t, `{"id":"knowledge-safe"}`)))
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bundle := crossBaseBundle(t)
tt.mutate(bundle)
if err := bundle.RemapKnowledgeBase(tt.target); err == nil {
t.Fatal("RemapKnowledgeBase() error=nil")
}
})
}
if err := (*DocumentBundle)(nil).RemapKnowledgeBase("prod-kb"); err == nil {
t.Fatal("nil bundle must be rejected")
}
}
// TargetBase is what every target-side write keys on.
func TestPlanItemTargetBaseFallsBackToTestedBase(t *testing.T) {
mapped := releaseworkflow.PlanItem{TestKnowledgeBaseID: "kb-safe", TargetKnowledgeBaseID: "prod-kb"}
if mapped.TargetBase() != "prod-kb" {
t.Fatalf("mapped TargetBase = %q", mapped.TargetBase())
}
unbound := releaseworkflow.PlanItem{TestKnowledgeBaseID: "kb-safe"}
if unbound.TargetBase() != "kb-safe" {
t.Fatalf("unbound TargetBase = %q, want the tested base", unbound.TargetBase())
}
}
// 范围改写只换身份,不改 schema 契约:改写后的快照若丢掉 SchemaVersion/Profile,
// 下游读到的就是"版本未知",而未知版本会被当作 0.7.1 处理——134 的归档于是被当成
// 74 搬,跨版本闸门形同不存在。
func TestRemapKnowledgeBasePreservesSchemaProfile(t *testing.T) {
bundle := crossBaseBundle(t)
bundle.Postgres.SchemaVersion = 134
bundle.Postgres.Profile = "v090"
if err := bundle.RemapKnowledgeBase("prod-kb"); err != nil {
t.Fatalf("remap: %v", err)
}
if bundle.Postgres.SchemaVersion != 134 || bundle.Postgres.Profile != "v090" {
t.Fatalf("remapped snapshot lost its schema profile: %d/%q",
bundle.Postgres.SchemaVersion, bundle.Postgres.Profile)
}
tables := map[string]bool{}
for _, table := range bundle.Postgres.Tables {
tables[table.Name] = true
}
if len(tables) != len(bundle.Postgres.Tables) {
t.Fatal("remap duplicated a table")
}
}